Wis*_*414 1 python inheritance class instance-variables parent
这是我正在尝试做的一个例子:
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 child
class Child():
def __init__(self, parent):
for key, val in vars(parent).items():
setattr(self, key, val)
print(self.parent_var) # successfully prints ABCD
foo = Parent()
Run Code Online (Sandbox Code Playgroud)
如果从父类继承,所有变量都将出现在子类中。在子类中使用 super init 确保父类实例化。
class Parent:
def __init__(self):
self.parent_var = 'ABCD'
class Child(Parent):
def __init__(self):
super().__init__()
child = Child()
print(child.parent_var)
Run Code Online (Sandbox Code Playgroud)
印刷:
'ABCD'