【发布时间】:2018-03-06 23:30:04
【问题描述】:
我有几个想要使用的子类,但它们都从它们的父类继承了一个方法,该方法的行为并不完全符合我的需要。
class ParentClass():
def __init__(self, value):
self.value = value
def annoying_funct(self):
print("I don't do quite what's needed and print {0}".format(self.value + 1))
def other_parent(self):
print("I do other useful things my children inherit")
class Child1(ParentClass):
def __init__(self, value, new_value1):
super(Child1, self).__init__(value)
self.new_value1 = new_value1
def other_child1(self):
print("I do useful child things")
class Child2(ParentClass):
def __init__(self, value, new_value2):
super(Child2, self).__init__(value)
self.new_value2 = new_value2
def other_child2(self):
print("I do other useful child things")
我想像这样覆盖annoying_funct():
def annoying_funct():
print("I behave the way I am needed to and print {0}".format(self.value))
ParentClass、Child1 和 Child2 来自一个非常复杂的库 (scikit-learn),所以我想让我的所有包装器尽可能薄。在根据需要更改父类的同时获取我的两个子类的功能的最简洁/最 Pythonic 的方法是什么?
到目前为止我的想法:
创建一个从父类继承的新类,它会覆盖我不喜欢的函数,然后为从新类和子类继承的子类创建包装类。
class NewParentClass(ParentClass):
def annoying_funct(self):
print("I behave the way I am needed to and print {0}".format(self.value))
class NewChild1(NewParentClass, Child1):
pass
class NewChild2(NewParentClass, Child2):
pass
我的困惑:
- 这是正确的方法吗?这似乎有点奇怪和笨拙。有没有更清洁的方法?
- 用于两个子类的语法是否正确?它适用于我,但让它们除了继承和传递之外什么都不做似乎有点奇怪。
- 让我的新父母继承前一位父母是正确的做法吗?代码在没有
parentClass和newParentClass之间的继承的情况下为孩子运行(例如def newParentClass():),但是如果有人试图创建newParentClass()的实例,则该函数将不起作用,因为它使用了不存在于那个班级(value)。如果我假设永远不会使用该类,那可以吗?
【问题讨论】:
-
为什么不覆盖child1和child2中的
annoying_funct? -
1)
child1和child2都是scikit-learn函数,因此newChild1和newChild2将是必要的 2) 更改annoying_funct两次似乎是多余的同样的事情,特别是因为annoying_funct是大约 200 行相当复杂的代码,我不想在两个不同的地方修复错误。
标签: python-3.x inheritance multiple-inheritance