【问题标题】:Declaring a class with an instance of it inside in Python在 Python 中声明一个带有它的实例的类
【发布时间】:2012-05-30 20:12:26
【问题描述】:

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

类似这样的:

class Foo:
    foo = Foo()

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

更新:

这就是我想要做的:

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

【问题讨论】:

  • 这有点像无限递归......你想完成什么?
  • 有人想知道为什么要创建类实例化的无限循环?
  • @ChristianWitts 我认为my answer 说明了一个你可能想要无限重复的例子:啤酒。
  • 在您的更新中,您的意思是创建对NPByteRange 类的引用还是对新的NPByteRange 实例的引用?

标签: python class instance


【解决方案1】:

如果您尝试在未声明 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>

最后,如果确实有必要将其设为 class 属性,那么,you can do that, too

【讨论】:

  • @user1426948 该评论应该是您问题的一部分,而不是对答案的评论。
  • @user1426948 是否有某种原因_fields_ 属性不能是实例属性或设置在__init__ 时间?
  • 好吧,我还是不确定,我只是在做一些实验,但我会尝试并告诉你。
猜你喜欢
  • 2015-04-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2013-07-06
  • 1970-01-01
  • 2017-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多