在Python中声明一个带有类实例的类 [英] Declaring a class with an instance of it inside in Python
问题描述
也许标题有点搞砸了,但是有没有办法在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?
类似这样的东西:
class Foo:
foo = Foo()
我知道口译员说Foo没有声明,但是有办法实现吗?
I know that the interpreter says that Foo is not declared but is there a way to achieve this?
更新:
这就是我要执行的操作:
This is what I'm trying to do:
class NPByteRange (Structure):
_fields_ = [ ('offset', int32),
('lenght', uint32),
('next', POINTER(NPByteRange)) ]
推荐答案
解释器只会介意尝试在未声明 Foo
的情况下执行此操作。在某些情况下是存在的。最简单的示例在方法中:
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>
最后,如果确实有必要将其作为 class 属性, ,您也可以这样做。
Finally, if it's truly necessary that it be a class property, well, you can do that, too.
这篇关于在Python中声明一个带有类实例的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!