3

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?

Something like this:

class Foo:
    foo = Foo()

I know that the interpreter says that Foo is not declared but is there a way to achieve this?

Update:

This is what I'm trying to do:

class NPByteRange (Structure): 
    _fields_ = [ ('offset', int32), 
                 ('lenght', uint32), 
                 ('next', POINTER(NPByteRange)) ]
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • This is kind of infinitely recursive... what are you trying to accomplish? – froadie May 30 '12 at 20:15
  • 3
    One has to wonder why you would want to create an infinite loop of Class instantiation ? – Christian Witts May 30 '12 at 20:15
  • Possible duplication of http://stackoverflow.com/questions/8370472/python3-and-recursive-class – iTayb May 30 '12 at 20:16
  • @ChristianWitts I think [my answer](http://stackoverflow.com/a/10823633/418413) illustrates one example where you might want an infinite recurrence: Beer. – kojiro May 30 '12 at 20:21
  • On your update, do you mean to create a reference to the `NPByteRange` class, or to a new `NPByteRange` instance? – kojiro May 30 '12 at 20:35
  • You may also want to read about other approaches to [linked lists in Python](http://stackoverflow.com/questions/280243). – kojiro May 30 '12 at 20:41

1 Answers1

4

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>

Finally, if it's truly necessary that it be a class property, well, you can do that, too.

Community
  • 1
  • 1
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • @user1426948 That comment should be part of your question, not a comment on an answer. – kojiro May 30 '12 at 20:28
  • @user1426948 is there some reason the `_fields_` property can't be an instance property or set at `__init__` time? – kojiro May 30 '12 at 20:34
  • Well I'm still not sure of it, I'm just doing some experiments but I'll try that and let you know. – user1426948 May 30 '12 at 20:37