Maybe the title is a little screwed up but is there a way to make an instance of a class inside the same class in Python?
Something like this:
class Foo:
foo = Foo()
I know that the interpreter says that Foo is not declared but is there a way to achieve this?
Update:
This is what I'm trying to do:
class NPByteRange (Structure):
_fields_ = [ ('offset', int32),
('lenght', uint32),
('next', POINTER(NPByteRange)) ]
解决方案
The interpreter only minds if you try to do it in a context where Foo is not declared. There are contexts where it is. The simplest example is in a method:
>>> class Beer(object):
... def have_another(self):
... return Beer()
...
>>> x=Beer()
>>> x.have_another()
If its important that the object be a property, you can just use the property builtin.
>>> class Beer(object):
... @property
... def another(self):
... return Beer()
...
>>> guinness=Beer()
>>> guinness.another
Finally, if it's truly necessary that it be a class property, well, you can do that, too.