1 回答

TA貢獻(xiàn)1831條經(jīng)驗 獲得超10個贊
如果您確定父類始終是Guy,您可以簡單地通過以下方式進(jìn)行注釋@Guy.greeting_decorator:
class Guy:
def __init__(self, name):
self.name = 'John'
def greeting_decorator(original_function):
def return_function(self, *args):
return f'Hi, I\'m {self.name}, fullname: {original_function(self, *args)}'
return return_function
class GuyWithSurname(Guy):
def __init__(self, name, surname):
super().__init__(name)
self.surname = surname
@Guy.greeting_decorator # <----- here
def __str__(self):
return f'{self.name} {self.surname}'
JohnDoe = GuyWithSurname('John', 'Doe')
這樣,當(dāng)你調(diào)用print(JohnDoe)它時就會輸出Hi, I'm John, fullname: John Doe.
請注意,我必須更改greeting_decorator和return_function參數(shù)才能正確處理self.
添加回答
舉報