python children 到 parent class 通讯

python children to parent class communication

到目前为止,我一直在学习 javascript,但我是 python 的新手,我想这样做:

def Node():
    def __init__(self):
        pass
    def callbacks(self):
        # i want this to change the value of the Tree property a to 2, how?
        self.self.a = 2
class Tree():
    def __init__(self):
        self.a = 1
    def printt(self):
        b = Node()
        b.callbacks()
        print(self.a)

a = Tree()
a.printt()

任何人都可以帮助或提出更好的方法来做到这一点,甚至可以解释它是否是一种设计模式?

我相信这是解决此类问题的方法,不知道是否有替代方法,例如 javascript

中的绑定方式
class Node:
    def __init__(self, parent_self):
        self.parent_self = parent_self
        pass
    def callbacks(self):
        # i want this to change the value of the Tree property a to 2, how?:w
        self.parent_self.set_a(2)
class Tree:
    def __init__(self):
        self.a = 1
        self.b = Node(self)
    def printt(self):
        self.b.callbacks()
        print(self.a)
    def set_a(self, val):
        self.a = val

a = Tree()
a.printt()