I build from classes some kind of tree. Each instance of a class (except the root) has an ancestor, and a variable containing an instance of a class must, when a function is called, like go_upper (which is a class method), change the value to an ancestor. I explain badly, sorry. Maybe it will be clearer if you look at the sample code.

This is how it looks like:

class Test: def __init__(self, parent): self.parent = parent def go_upper(self): self = self.parent class _RootTest(Test): def __init__(self): pass first = _RootTest() second = Test(first) second.go_upper() # Переменной second должно присвоиться first 

How can you implement something like that?

  • one
    What does it mean to change the value of an instance of a class? It does not have a value, it is an object that has attributes, methods. In this case, you simply override the name self in the scope of the go_upper method. - mkkik
  • I put it wrong. I'm trying to change the value of a variable containing an instance of a class - Semior
  • one
    Then it is not clear why the class method is needed at all. You will always know the instance of the class, the link to which you want to get. - mkkik
  • It might be better to do second = second.parent instead - Xander
  • There is such a moment when you do not want to do it normally, but you want to do it beautifully. I think this is the case. Class method is needed for beauty, it does not do anything significant. As described above, the same action should be performed as with second = second.parent. If you make a separate method for this - the readability of the code will increase - Semior

0