这是我正在尝试做的一个例子:
class Parent():
def __init__():
self.parent_var = 'ABCD'
x = Child(self) # self would be passing this parent instance
class Child():
def __init__(<some code to pass parent>):
print(self.parent_var)
foo = Parent()
Run Code Online (Sandbox Code Playgroud)
现在我知道您在想什么,为什么不将parent_var 本身传递给子实例呢?我的实际实现在 Parent 中有超过 20 个类变量。我不想手动将每个变量传递给在 Parent 中实例化的 Child 实例的 __init__ - 有没有办法使所有 Parent 类变量可供 Child 使用?
编辑 - 已解决:这是我发现有效的方式:
class Parent():
def __init__(self):
self.parent_var = 'ABCD' # but there are 20+ class vars in this class, not just one
x = Child(self) # pass this parent instance to …Run Code Online (Sandbox Code Playgroud)