我有一个基类和一些用Python派生的类:
class Base:
def Foo(self):
pass
# First derived class
class Der1(Base):
def OwnFoo(self):
# Do something 1
def OwnFoo2(self):
# Do something 2
def Foo(self):
# Do something 3
# Second derived class
class Der2(Base):
def OwnFoo(self):
# Do something 1
def OwnFoo2(self):
# Do something 2
def Foo(self):
# Do something 3
问题是:
我在Der1
中有一些预定义的代码。几乎所有来自Der2
的函数都执行相同的操作。我怎么能用更少的代码来写呢?你知道吗
我无法将该代码添加到父级。不能碰父类。你知道吗
例如,Der2.OwnFoo
与Der1.OwnFoo
做的相同,也许python中有某种构造只是为了从第一个类调用OwnFoo
,而不是再次编写代码?你知道吗
我无法更改Der1
和Der2
的父级!应该是Base
。你知道吗
把
Der2
变成Der1
的子类,就完成了。你知道吗在
Der2
中您想要专门化的任何行为都可以添加到类定义中。如果在Der2
(例如Der2.OwnFoo()
)中创建一个同名的新方法,那么它将重载从Der1
继承的默认方法。你知道吗编辑:如果不能更改父类,请将所有要继承的行为放在基类中,记住可以重载或自定义子类中的任何方法。你知道吗
在代码中:
您可以使用一个“技巧”来调用从父级继承的原始方法,捕获返回值,然后自定义行为。只有当方法实际返回一个值时,这才有效;如果方法在类中操纵属性,这可能是危险的,除非这是您想要的和期望的。你知道吗
在代码中:
这是家庭作业吗?你知道吗
看
Der2
的第一行:什么说明它的父级是什么(例如,它派生的类及其方法和属性)?你怎么能改变这个?你知道吗
因为不能更改继承结构,所以创建一个包含公共代码的助手类,并通过composition而不是继承来包含它。你知道吗
当然,可以将引用传递给父级而不是字符串。我这样做只是为了演示。你知道吗
用法:
输出:
相关问题 更多 >
编程相关推荐