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

2024-10-03 23:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种很好的方法从父类中重用代码,而不仅仅是复制粘贴父类中的所有代码,如果要更改代码中的几行代码,则替换一些代码?p>

  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

Tags: 方法代码selfreturnexampledeflineclass
2条回答

您可以使用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())具有相同的名称、相同的参数或签名以及相同的返回类型(或子类型)时,则称子类中的方法覆盖了超类中的方法。执行的方法的版本将由用于调用它的对象确定

此外,如果您希望您的子类成为父类的副本,则只需执行以下操作:

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

如果您想完全更改子类中的属性,而不是像上面那样递增/递减它,只需将+=符号替换为=

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

相关问题 更多 >