3

也许标题有点搞砸了,但是有没有办法在 Python 的同一个类中创建一个类的实例?

像这样的东西:

class Foo:
    foo = Foo()

我知道解释器说 Foo 没有声明,但有没有办法实现这一点?

更新:

这就是我想要做的:

class NPByteRange (Structure): 
    _fields_ = [ ('offset', int32), 
                 ('lenght', uint32), 
                 ('next', POINTER(NPByteRange)) ]
4

1 回答 1

4

如果您尝试在Foo未声明的上下文中执行此操作,解释器只会介意。有它所在的上下文。最简单的例子是在一个方法中:

>>> class Beer(object):
...   def have_another(self):
...     return Beer()
... 
>>> x=Beer()
>>> x.have_another()
<__main__.Beer object at 0x10052e390>

如果对象是属性很重要,则可以使用property内置函数。

>>> class Beer(object):
...   @property
...   def another(self):
...     return Beer()
... 
>>> guinness=Beer()
>>> guinness.another
<__main__.Beer object at 0x10052e610>

最后,如果确实有必要将它作为属性,那么您也可以这样做

于 2012-05-30T20:18:47.277 回答