Can a python class contain an instance of itself as a data container

Can a python class contain an instance of itself, since a data container might look like this?

class A:
    def __init__(self, val):
        self.a = A(val)
        self.val = val

aa = A(2) 
#this will cause RuntimeError: maximum recursion depth exceeded

my goal is to use this class as a data container that contains a copy inside if it is included in order to reduce the effect of deepcopy. it can be used as a "cancel" chain, it makes it possible to get the value of the initialization value, when necessary.

is such an action possible?

thank

Kc

+3
source share
3 answers

This will not work for the reason already indicated:

  • Python sees A(2)and calls A.__init__.
  • A.__init__causes A(val).
  • A(val)causes A.__init__.
  • Goto 2

, , , val; , , val 3 , 2. :

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

  • A( object ): object. , .
  • @property: python, , A.val, A.val() . ; property .
  • @val.setter: , Python, , A.val, . A.val .
+5

, , self.a self.a, . , , , - :

class A:
    def __init__(self, val, copy = True):
        if copy:
            self.a = A(val, False)
        self.val = val
+1

Yes, a class can contain an instance of itself; you simply cannot create it when you initiate it for the reasons described by others.

For example, this class will do this,

class A:
    def __init__(self,value):
        self.value=value
    def setProperty(self,subvalue):
        self.innerInstance=A(subvalue)

Then you can create an instance and set its internal copy as follows:

>>>OuterInstance=A(123)
>>>OuterInstance.setProperty(456)

And make sure it worked with:

>>>OuterInstance.innerInstance.value
456
+1
source

Source: https://habr.com/ru/post/1757305/


All Articles