473,385 Members | 1,752 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Reference class in class creation

Hi,

I want to reference a class itself in its body:

class SomeElement(object):
def __init__(self, mycontainer):
self.mycontainer=mycontainer

class SomeContainer(object):
a = SomeElement(SomeContainer)
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(object):
----6 a = SomeElement(SomeContainer)
7
8

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

Unfortunatly the obvious:

class SomeContainer(object):
def __init__(self):
self.a = SomeElement(SomeContainer)

is not possible because of other constraints.

--
Servus, Gregor

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

I want to reference a class itself in its body:

class SomeElement(object):
def __init__(self, mycontainer):
self.mycontainer=mycontainer

class SomeContainer(object):
a = SomeElement(SomeContainer)
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(object):
----6 a = SomeElement(SomeContainer)
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.comwrote:
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(object):
def __init__(self, mycontainer):
self.mycontainer=mycontainer

class SomeContainer(object):
a = SomeElement(SomeContainer)
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(object):
def __init__(self):
self.a = SomeElement(SomeContainer)
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__(metatype,name,bases,clsdict):
# do some weird stuff here
return type.__new__(metatype,name,bases,clsdict)

You could change it to look like this instead:

def __new__(metatype,name,bases,clsdict):
# do some weird stuff here
cls = type.__new__(metatype,name,bases,clsdict)
cls.a = SomeContainer(cls)
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__(metatype,name,bases,dict):
cls = GivenMetaclass.__new__(metatype,name,bases,dict)
cls.a = SomeContainer(cls)
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_attrs['widget_edit'])
(bases[0].save)
return type.__new__(meta, class_name, bases, new_attrs)
class MotourForm(TableForm):
template = "motour.templates.motourform"
params = ["delete_attrs","cancel_attrs"]

member_widgets = ["delete","cancel"]
cancel = ResetButton(name="cancel")
delete_attrs = {}

def __init__(self, controller, *args, **kwargs):
super(MotourForm, self).__init__(action = "%s/save" %
controller.get_path, *args, **kwargs)
self.controller = controller
self.delete = LinkButtonAsk(name="delete", caption =
_(u"Löschen"), question = _(u"Wirklich loeschen"),
link = "%s/delete" % controller.get_path())

self.cancel_attrs = dict(onClick="self.location.href='%s/back';"
% controller.get_path())

class TourEdit(MotourForm):
template = "motour.templates.touredit"
params = ["tourposvalue"]

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

class Tour(MotourController):
__metaclass__ = ControllerMeta
sqlobjectclass = model.Tour

#Here is the problem
widget_edit = TourEdit(controller=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(MotourController):
pass

Tour.sqlobjectclass = model.Tour
Tour.widget_edit = TourEdit(controller=Tour, name = "tourheader", ...)

Tour = validate(Tour)

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

def __new__(metatype,name,bases,clsdict):
# do some weird stuff here
cls = type.__new__(metatype,name,bases,clsdict)
cls.a = SomeContainer(cls)
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__(meta, class_name, bases, new_attrs)
cls.__classinit__.im_func(cls, new_attrs)
cls.save = validate(cls.widget_edit)(bases[0].save)
return cls

and the Tour Class:

class Tour(MotourController):
__metaclass__ = ControllerMeta
sqlobjectclass = model.Tour

def __classinit__(cls, newattrs):
cls.widget_edit = TourEdit(controller=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.comwrote in message
news:a1***************************@news.chello.at. ..
Hi,

I want to reference a class itself in its body:

class SomeElement(object):
def __init__(self, mycontainer):
self.mycontainer=mycontainer

class SomeContainer(object):
a = SomeElement(SomeContainer)
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(object):
----6 a = SomeElement(SomeContainer)
7
8

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

Unfortunatly the obvious:

class SomeContainer(object):
def __init__(self):
self.a = SomeElement(SomeContainer)

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
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...
4
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...
6
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...
11
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
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...
9
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
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"? ...
1
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...
0
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...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.