【发布时间】:2018-02-22 14:36:58
【问题描述】:
假设您在某些模块 parents.py 中有两个具有相同接口的父类
class Mother:
def __init__(self):
print("mother")
class Father:
def __init__(self):
print("father")
而你想使用一个子类,它可以对两个类都进行操作,比如
import parents
class Child:
def __init__(self,parent_choice):
parents.parent_choice.__init__()
是否可以选择正确的父对象作为变量来创建这样的子对象?像
import child
son_of_your_mother = Child(Mother)
最好的方法是为每个父级设置单独的模块(.py 文件)(如我的示例中所示)。 欢迎任何其他方法解决这个问题,只要它使两个父类分开(离婚通常对孩子有好处)。
【问题讨论】:
-
parents.parent_choice.__init__()行出现错误。请不要编写明显不起作用的代码。 -
抱歉对我来说不是那么明显。通常我会做 super().__init__(**args)。怎么不等价?
-
不是很明显???只需测试您的代码!
-
问题出在son_of_your_mother = child(mother),mother应该是mother的一个实例,而不是你提到的那一行。而且我没有实例化它,因为目标是在执行此操作时实例化一个对象,但继承类属性。当然代码不会像我说的那样工作,否则我不会有任何疑问
标签: python class parent-child