473,895 Members | 2,373 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reference class in class creation

Hi,

I want to reference a class itself in its body:

class SomeElement(obj ect):
def __init__(self, mycontainer):
self.mycontaine r=mycontainer

class SomeContainer(o bject):
a = SomeElement(Som eContainer)
Unfortunatly this does not work since the name SomeContainer is not
definied at class creation time of SomeContainer:

/tmp/python-9309vMe.py in SomeContainer()
4
5 class SomeContainer(o bject):
----6 a = SomeElement(Som eContainer)
7
8

NameError: name 'SomeContainer' is not defined
How to do this?

Unfortunatly the obvious:

class SomeContainer(o bject):
def __init__(self):
self.a = SomeElement(Som eContainer)

is not possible because of other constraints.

--
Servus, Gregor

Nov 21 '06 #1
9 2916
Gregor Horvath wrote:
Hi,

I want to reference a class itself in its body:

class SomeElement(obj ect):
def __init__(self, mycontainer):
self.mycontaine r=mycontainer

class SomeContainer(o bject):
a = SomeElement(Som eContainer)
Unfortunatly this does not work since the name SomeContainer is not
definied at class creation time of SomeContainer:

/tmp/python-9309vMe.py in SomeContainer()
4
5 class SomeContainer(o bject):
----6 a = SomeElement(Som eContainer)
7
8

NameError: name 'SomeContainer' is not defined
How to do this?
Anything wrong with:

class Foo(object):
pass

Foo.a = Foo

?

Diez

Nov 21 '06 #2
Diez B. Roggisch schrieb:
Anything wrong with:

class Foo(object):
pass

Foo.a = Foo

?
Thanks.
The problem with this is that there is also metaclass hacking involved
which relies on "a" 's creation in the class body. In your suggestion
"a" is not present when __new__ of the metaclass is called.

--
Servus, Gregor
Nov 21 '06 #3
Gregor Horvath <gh@gregor-horvath.comwrot e:
Diez B. Roggisch schrieb:
>Anything wrong with:

class Foo(object):
pass

Foo.a = Foo

?

Thanks.
The problem with this is that there is also metaclass hacking involved
which relies on "a" 's creation in the class body. In your suggestion
"a" is not present when __new__ of the metaclass is called.
The class doesn't exist until the metaclass has created it, so you can't
expect to have any references to it.

You've told us that what you are trying to do doesn't work, but you haven't
said why you want to do it. What is the problem you are really trying to
solve?
Nov 21 '06 #4
Gregor Horvath wrote:
Hi,

I want to reference a class itself in its body:

class SomeElement(obj ect):
def __init__(self, mycontainer):
self.mycontaine r=mycontainer

class SomeContainer(o bject):
a = SomeElement(Som eContainer)
Are you sure you want to
1/ create SomeElement as a *class* attribute (that is, an attribute
shared by all instances of SomeContainer) and
2/ pass the SomeContainer *class* to the initializer of SomeElement ?

Well, anyway:
>
Unfortunatly this does not work since the name SomeContainer is not
definied at class creation time of SomeContainer:
indeed.
>
How to do this?

Unfortunatly the obvious:

class SomeContainer(o bject):
def __init__(self):
self.a = SomeElement(Som eContainer)
You do understand that declaring 'a' as an attribute of self creates an
instance attribute, while your above snippet creates 'a' as a class
attribute, do you ?
is not possible because of other constraints.
Care to elaborate ?

FWIW, there are technical answers to your question (look for descriptors
and/or metaclasses)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Nov 21 '06 #5

Gregor Horvath wrote:
Diez B. Roggisch schrieb:
Anything wrong with:

class Foo(object):
pass

Foo.a = Foo

?

Thanks.
The problem with this is that there is also metaclass hacking involved
which relies on "a" 's creation in the class body. In your suggestion
"a" is not present when __new__ of the metaclass is called.
The metaclass's __new__ returns the class object. This is the first
time the object is available; it's impossible to access before that,
but you can get at it before __new__ exits. Most metaclass __new__
functions look like this:

def __new__(metatyp e,name,bases,cl sdict):
# do some weird stuff here
return type.__new__(me tatype,name,bas es,clsdict)

You could change it to look like this instead:

def __new__(metatyp e,name,bases,cl sdict):
# do some weird stuff here
cls = type.__new__(me tatype,name,bas es,clsdict)
cls.a = SomeContainer(c ls)
return cls

Or, if you can't change the metaclass, you can subclass it and override
__new__ to get at cls before __new__ exits:

def __new__(metatyp e,name,bases,di ct):
cls = GivenMetaclass. __new__(metatyp e,name,bases,di ct)
cls.a = SomeContainer(c ls)
return cls

If the "metaclass hacking" you describe is setting __metaclass__ to a
function (i.e., not metaclass hacking), then same thing applies, just
modify or wrap the function to get at the class object and do what you
need to do.
Carl Banks

Nov 21 '06 #6
Duncan Booth schrieb:
You've told us that what you are trying to do doesn't work, but you haven't
said why you want to do it. What is the problem you are really trying to
solve?
I need this for some complicated turbogears controller classes for a
generic framework.

The point is that I have a formwidget which has to know which controller
it belongs to. (Because the controller knows the path, the
sqlobjectclass etc.). The widget has to be created at class creation
time of the controller, because there is a metaclass which ensures
validation of the formwidget. (Necessary because the controller is
inherited)

Basically and stripped down this looks like this:

class ControllerMeta( type):
def __new__(meta, class_name, bases, new_attrs):
new_attrs["save"] = validate(new_at trs['widget_edit'])
(bases[0].save)
return type.__new__(me ta, class_name, bases, new_attrs)
class MotourForm(Tabl eForm):
template = "motour.templat es.motourform"
params = ["delete_attrs", "cancel_att rs"]

member_widgets = ["delete","cance l"]
cancel = ResetButton(nam e="cancel")
delete_attrs = {}

def __init__(self, controller, *args, **kwargs):
super(MotourFor m, self).__init__( action = "%s/save" %
controller.get_ path, *args, **kwargs)
self.controller = controller
self.delete = LinkButtonAsk(n ame="delete", caption =
_(u"Löschen"), question = _(u"Wirklich loeschen"),
link = "%s/delete" % controller.get_ path())

self.cancel_att rs = dict(onClick="s elf.location.hr ef='%s/back';"
% controller.get_ path())

class TourEdit(Motour Form):
template = "motour.templat es.touredit"
params = ["tourposval ue"]

member_widgets = ["tourpos"]
tourpos = DataGridAED()

class Tour(MotourCont roller):
__metaclass__ = ControllerMeta
sqlobjectclass = model.Tour

#Here is the problem
widget_edit = TourEdit(contro ller=Tour, name = "tourheader ",
fields = [Label(name="id" , label=_("Tour-ID")),
TextField(name= "name")])

I hope it's not to confusing.
Thank's for your help.

--
Greg
Nov 21 '06 #7
Is there a reason why don't you drop the metaclass and perform the
validation step after the class has been created using a generic
function?

class Tour(MotourCont roller):
pass

Tour.sqlobjectc lass = model.Tour
Tour.widget_edi t = TourEdit(contro ller=Tour, name = "tourheader ", ...)

Tour = validate(Tour)

Nov 21 '06 #8
Carl Banks schrieb:
You could change it to look like this instead:

def __new__(metatyp e,name,bases,cl sdict):
# do some weird stuff here
cls = type.__new__(me tatype,name,bas es,clsdict)
cls.a = SomeContainer(c ls)
return cls
Cark, many thanks for your suggestion, it solved my problem.

I changed the metaclass:

class ControllerMeta( type):
def __new__(meta, class_name, bases, new_attrs):
cls = type.__new__(me ta, class_name, bases, new_attrs)
cls.__classinit __.im_func(cls, new_attrs)
cls.save = validate(cls.wi dget_edit)(base s[0].save)
return cls

and the Tour Class:

class Tour(MotourCont roller):
__metaclass__ = ControllerMeta
sqlobjectclass = model.Tour

def __classinit__(c ls, newattrs):
cls.widget_edit = TourEdit(contro ller=cls, name = "tourheader ",
fields = [Label(name="id" )])
And this seems to work fine.

Thanks
--
Greg
Nov 21 '06 #9
class Foo(object):
me = None
def __init__(self):
Foo.me = self

easy!

"Gregor Horvath" <gh@gregor-horvath.comwrot e in message
news:a1******** *************** ****@news.chell o.at...
Hi,

I want to reference a class itself in its body:

class SomeElement(obj ect):
def __init__(self, mycontainer):
self.mycontaine r=mycontainer

class SomeContainer(o bject):
a = SomeElement(Som eContainer)
Unfortunatly this does not work since the name SomeContainer is not
definied at class creation time of SomeContainer:

/tmp/python-9309vMe.py in SomeContainer()
4
5 class SomeContainer(o bject):
----6 a = SomeElement(Som eContainer)
7
8

NameError: name 'SomeContainer' is not defined
How to do this?

Unfortunatly the obvious:

class SomeContainer(o bject):
def __init__(self):
self.a = SomeElement(Som eContainer)

is not possible because of other constraints.

--
Servus, Gregor

Nov 21 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1545
by: mortoray | last post by:
Throughout the PHP manual, and normal code, one finds this construct: $var = array( ... ); However, as far as I can tell this is quite inefficient, since it always means two arrays are being created. The right-side array is created, and then copied to the left-side variable. Thus one would expect the normal syntax should be: $var =& array( ... );
4
1144
by: DS | last post by:
I've got a question about how I can go about nesting a reference type in an object of an instantiated class alongside value types. This may seem a bit vague so I'll give an example: public class Cow { private string farm; private int brandNumber; public Cow() {
6
5587
by: ged | last post by:
Hi, i am a oo (c#) programmer, and have not used javascript for a while and i cant work out how javascript manages its references. Object References work for simple stuff, but once i have an object collection and stanrd using it it starts to fall apart. Clearly there is something about javascript's usage of passing "By ref" that i am not getting. i have had a look on the web and found some examples, but i cant see why my code does not...
11
2416
by: anongroupaccount | last post by:
What measures should be taken to avoid this sort of thing? class Base { }; class Derived1 : public Base { private: int i, j, k;
3
4421
by: Richard Lewis Haggard | last post by:
We are having a lot of trouble with problems relating to failures relating to 'The located assembly's manifest definition with name 'xxx' does not match the assembly reference" but none of us here really understand how this could be an issue. The assemblies that the system is complaining about are ones that we build here and we're not changing version numbers on anything. The errors come and go with no apparent rhyme or reason. We do not...
9
6204
by: | last post by:
Hi How to get a reference to main form in a Windows Form 2.0 Application? I'm making a a library and I need a reference to the main form of the application that is using that library. TIA
2
1826
by: Grizlyk | last post by:
Hello. Can compiler garantee equal optimization in the following example for reference "named_ref" as for "named_function"? How I can declare that the "named_ref" always will returns "*this"? // *** class A { public:
1
1512
by: Anonymous | last post by:
I have been trying to write a template class for a shared memory container, over the last few days - but I keep getting numerous compiler errors e.g: Error: syntax error : identifier 'myStaticShmemAllocator<void>' Error: 'AllocationPolicy' : undeclared identifier Here is the truncated code below -
0
1395
balabaster
by: balabaster | last post by:
Hi all, I'm creating a class factory and a bunch of adapters to allow in house applications to communicate with mobile applications over different cellular networks. I've got my class factory and interface definition in a single assembly. The class factory will instantiate the correct adapter for communication with a mobile device at runtime. We're doing it this way because we won't know which cellular network we're communicating over...
0
9990
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11249
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10935
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10473
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9649
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7177
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5863
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4689
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4285
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.