Can a class contain an instance of itself as a data container?
This won't work, for the reason already given:
- Python sees
A(2)
and callsA.__init__
. A.__init__
callsA(val)
.A(val)
callsA.__init__
.- GOTO 2
I assume you're doing this so that you have a log of what val
has been; that is, if sometime later you decide that you want val
to be 3
instead, you don't throw away the original value 2
. How about:
Code
class A( object ):
@property
def val( self ):
return self.history[ -1 ]
@val.setter
def val( self, value ):
self.history.append( value )
def __init__( self, val ):
self.history = [ ]
self.val = val
Explanation
A( object )
: classes should now inherit fromobject
. Just because, basically.@property
: this tells python that every time we ask for A.val, it should call A.val() and return the result. This is a decorator; look up theproperty
builtin function for more information.@val.setter
: this is similar to the above, but tells Python that every time we try to assign toA.val
it should call the following function instead. Instead of settingA.val
, it appends the value to the history list.
Yes, a class can contain an instance of itself, you just can't create it on initiation for the reasons described by others.
For example this class will do it,
class A:
def __init__(self,value):
self.value=value
def setProperty(self,subvalue):
self.innerInstance=A(subvalue)
You can then instantiate it and set its inner copy of itself like this:
>>>OuterInstance=A(123)
>>>OuterInstance.setProperty(456)
And verify it worked with:
>>>OuterInstance.innerInstance.value
456