也许标题有点搞砸但有没有办法在Python的同一个类中创建一个类的实例?
这样的事情:
class Foo:
foo = Foo()
我知道解释器说Foo没有声明,但有没有办法实现这个目标?
更新
这就是我要做的事情:
class NPByteRange (Structure):
_fields_ = [ ('offset', int32),
('lenght', uint32),
('next', POINTER(NPByteRange)) ]
答案 0 :(得分: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>
最后,如果确实需要它是类属性,那么,you can do that, too。