如何有效地重用父类中的代码?(python)



如果我想更改代码中间的几行代码,除了复制粘贴父类中的所有代码并替换一些代码之外,还有什么好的方法可以重用父类中代码吗?

  1. 我不能直接更改父类中的代码
  2. 大多数代码是相同的,但只有少数代码行是不同的
  3. 真正的代码是数百行代码,父类和子类之间只有几行代码不同

父类:

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()语法从子方法调用重载方法的父版本,然后对返回的值执行其他操作。这与你所要求的不完全相同,但我相信这是你在实际问题上能做的最好的事情。

示例:

class Parent:
def perform_task(self, x):
x += 10
return x
class Child(Parent):
def perform_task(self, x):
x = super().perform_task(x)
x *= 2
return x
c = Child()
print(c.perform_task(5))

输出:

30

您可以执行以下操作,以避免重写父类中的代码,同时稍微更改子类:

class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
def display(self):
print('Eye color: {0} ---- Length: {1}'.format(self.eye_color, self.length))

class Child(Parent):
def __init__(self, gender, parent):
super().__init__(parent.eye_color, parent.length)
self.gender = str(gender) #child slightly changed with the addition of new attribute
def display(self):
super().display()
print('Gender: {0}'.format(self.gender))
x = Parent("Blue", 2)
y = Child("Men", x)
print(x.length, x.eye_color)
print(y.gender, y.length)
x.display()
print()
y.display()

输出

2 Blue
Men 2
Eye color: Blue ---- Length: 2
Eye color: Blue ---- Length: 2
Gender: Men

当子类中的一个方法与其超类中的方法(如方法display()(具有相同的名称、相同的参数或签名以及相同的返回类型(或子类型(时,则称子类中方法覆盖超类中方法。执行的方法的版本将由用于调用它的对象决定

此外,如果您希望您的子类是父类的COPY,那么您只需执行以下操作:

class Parent:
def __init__(self, eye_color, length):
self.eye_color = str(eye_color)
self.length = length
def display(self):
print('Eye color: {0} ---- Length: {1}'.format(self.eye_color, self.length))
class Child(Parent):
pass
y = Parent ('stack',3)
x = Child('Overflow',2)
print(x.length, x.eye_color)
x.display()
y.display()

如果不想向类中添加任何其他属性或方法,请使用pass关键字。

您还可以通过执行以下操作来更改和附加子类中超类的属性:

class Child(Parent):
def __init__(self, gender, parent):
super().__init__(parent.eye_color, parent.length)
self.gender = str(gender)
parent.length += 2
x = Parent("Blue", 2)
y = Child("Men", x)
print(x.length, x.eye_color)
print(y.eye_color, y.length)
x.display()
y.display()

这将使长度增加2,将显示输出转换为:

2 Blue
Blue 3
Eye color: Blue ---- Length: 2
Eye color: Blue ---- Length: 3

如果你想完全改变子类中的一个属性,而不是像我上面做的那样递增/递减,只需用=代替+=符号

关于如何在子类中附加和重用代码,您还有其他问题吗?

最新更新