Declaring A Class With An Instance Of It Inside In Python
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 th
Solution 1:
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()
<__main__.Beer object at 0x10052e390>
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
<__main__.Beer object at 0x10052e610>
Finally, if it's truly necessary that it be a class property, well, you can do that, too.
Post a Comment for "Declaring A Class With An Instance Of It Inside In Python"