有没有一种很好的方法从父类中重用代码,而不仅仅是复制粘贴父类中的所有代码,如果要更改代码中的几行代码,则替换一些代码?p>
父类:
class Parent():
def example(self):
doSomething1()
doSomething2()
...
doSomething100()
doSomething101()
...
doSomething200()
return
儿童班:
class Child(Parent):
def example(self):
doSomething1()
doSomething2()
...
doSomething100()
doSomethingNew() #add a new line
#doSomething101() #delete a line
doSomethingReplace() #replace a line
...
doSomething200()
return
您可以使用
super()
语法从子级调用重载方法的父版本,然后对返回的值执行其他操作。这与你的要求并不完全相同,但我相信这是你在实际问题上所能做的最好的事情例如:
输出:
为了不重写父类中的代码,您可以执行以下操作,同时稍微更改子类:
输出
当子类中的方法与其超类中的方法(如方法
display()
)具有相同的名称、相同的参数或签名以及相同的返回类型(或子类型)时,则称子类中的方法覆盖了超类中的方法。执行的方法的版本将由用于调用它的对象确定此外,如果您希望您的子类成为父类的副本,则只需执行以下操作:
如果不想向类添加任何其他属性或方法,请使用
pass
关键字您还可以通过以下操作更改和附加子类中超类的属性:
这将使长度增加2,从而将显示输出转换为:
如果您想完全更改子类中的属性,而不是像上面那样递增/递减它,只需将
+=
符号替换为=
关于如何在子类中追加和重用代码,您还有其他问题吗
相关问题 更多 >
编程相关推荐