现行守则是:
class Base:
def hello(self):
print('hello')
class A(Base):
def greet(self):
self.hello()
print('how are you?')
class B(Base):
def greet(self):
self.hello()
print('how are you doing?')当调用self.hello()时,我如何编写代码来实现这个调用self.greet(),而不是在每个A类和B类中添加self.hello()?
我想遵循不要重复自己的原则。
发布于 2022-10-17 09:04:48
您有重复代码的原因是因为您正在重新定义代码中的“问候”。通过认识到greet总是由"hello“消息后面跟着一个问题组成,您可以在基类中实现该通用功能,并要求在子类中实现实际的问题。
这个简单示例的代码略多一点,但它演示了一般原则:
class Base:
def hello(self):
print('hello')
def question(self):
# this should be implemented in the derived classes
raise NotImplementedError
def greet(self):
self.hello()
self.question()
class A(Base):
def question(self):
print('how are you?')
class B(Base):
def question(self):
print('how are you doing?')
a = A()
b = B()
a.greet()
b.greet()注意:没有来定义基类中的question()方法(您可以省略它,代码仍然可以工作),但是它有助于记录子类必须定义这个函数,并且它会打印一个更有用的错误消息,以防您意外地试图调用基类的对象上的question()方法。它还可以避免在运行指针(如pylint或pycodestyle)时发出警告,并在使用IDE (如Visual )时改进语法突出显示/自动完成。
发布于 2022-10-17 08:56:46
在这个场景中,我认为您希望定义Base类中的基本行为,允许后续类通过添加额外的逻辑来扩展到该行为,而不是替换它。
以下是实现这一目标的一种方法:
class Base:
def hello(self):
print('hello')
def greet(self):
self.hello()
class A(Base):
def greet(self):
super().greet()
print('how are you?')
class B(Base):
def greet(self):
super().greet()
print('how are you doing?')即使重复对super().greet()的调用,这也是在Python中进行调用的方法--因为需要显式调用它(例如,在Java中,父调用总是被调用的)。
https://stackoverflow.com/questions/74094443
复制相似问题