Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中声明一个类,其中包含一个实例_Python_Class_Instance - Fatal编程技术网

在Python中声明一个类,其中包含一个实例

在Python中声明一个类,其中包含一个实例,python,class,instance,Python,Class,Instance,也许标题有点搞错了,但是有没有办法在Python的同一个类中创建一个类的实例 大概是这样的: class Foo: foo = Foo() 我知道口译员说Foo没有声明,但有没有办法做到这一点 更新: 这就是我想做的: class NPByteRange (Structure): _fields_ = [ ('offset', int32), ('lenght', uint32), ('next', PO

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

大概是这样的:

class Foo:
    foo = Foo()
我知道口译员说Foo没有声明,但有没有办法做到这一点

更新:

这就是我想做的:

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

只有当您试图在未声明
Foo
的上下文中执行此操作时,解释器才会介意。这是有背景的。最简单的例子是在一个方法中:

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

最后,如果真的需要它是一个类属性,那么,。

这是一种无限递归。。。你想实现什么?你一定想知道为什么你想创建一个无限循环的类实例化?我认为@ChristianWitts的可能重复说明了一个你可能想要无限循环的例子:Beer。在你的更新中,你的意思是创建一个对
NPByteRange
类的引用吗,或者新的
NPByteRange
实例?@user1426948该注释应该是您问题的一部分,而不是对答案的注释。@user1426948是否有某种原因
\u fields\u
属性不能成为实例属性或设置为
\u初始\u
时间?我仍然不确定,我只是在做一些实验,但我会试试,然后告诉你。
>>> class Beer(object):
...   @property
...   def another(self):
...     return Beer()
... 
>>> guinness=Beer()
>>> guinness.another
<__main__.Beer object at 0x10052e610>