現有代碼是:
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(),而不是self.hello()在每個 A 類和 B 類中添加?
我想遵循不要重復自己 (DRY)原則。
uj5u.com熱心網友回復:
您有重復代碼的原因是因為您正在重新定義代碼中的“問候”。通過認識到問候總是由“你好”訊息后跟一個問題組成,您可以在基類中實作該通用功能,并要求在子類中實作實際問題。
這個簡單示例的代碼略多一些,但它演示了一般原則:
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()在基類的物件上呼叫該方法。它還可以在運行 linter(例如pylintor pycodestyle)時避免警告,并在您使用 IDE(例如 Visual Studio Code)時改進語法突出顯示/自動完成。
uj5u.com熱心網友回復:
在這種情況下,我認為您希望在類中定義基本行為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://www.uj5u.com/ruanti/524301.html
標籤:Python遗产干燥
