Declaring a class with an instance of it inside in

2019-07-02 04:51发布

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)) ]

1条回答
\"骚年 ilove
2楼-- · 2019-07-02 05:26

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.

查看更多
登录 后发表回答