使用父类的装饰器方法转换类方法

def greeting_decorator(original_function):

    def return_function(*args):

        name = 'John'

        return f'Hi, I\'m {name}, fullname: {original_function(*args)}'

    return return_function


@greeting_decorator

def greeting(name, surname):

    return f'{name} {surname}'


print(greeting('John', 'Doe'))

上面,我有一个简单的装饰器函数,可以按预期工作。

我想做类似的事情,但是使用继承的类。我该如何继承这样的装饰器函数:


class Guy:


    def __init__(self, name):

        self.name = 'John'


    def greeting_decorator(self, original_function):

        def return_function(*args):

            return f'Hi, I\'m {self.name}, fullname: {original_function(*args)}'

        return return_function



class GuyWithSurname(Guy):


    def __init__(self, name, surname):

        super().__init__(name)

        self.surname = surname


    @greeting_decorator # <----- here

    def __str__(self):

        return f'{self.name} {self.surname}'

    

JohnDoe = GuyWithSurname('John', 'Doe')

print(JohnDoe)


眼眸繁星
浏览 93回答 1
1回答

慕哥6287543

如果您确定父类始终是Guy,您可以简单地通过以下方式进行注释@Guy.greeting_decorator:class Guy:&nbsp; &nbsp; def __init__(self, name):&nbsp; &nbsp; &nbsp; &nbsp; self.name = 'John'&nbsp; &nbsp; def greeting_decorator(original_function):&nbsp; &nbsp; &nbsp; &nbsp; def return_function(self, *args):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return f'Hi, I\'m {self.name}, fullname: {original_function(self, *args)}'&nbsp; &nbsp; &nbsp; &nbsp; return return_functionclass GuyWithSurname(Guy):&nbsp; &nbsp; def __init__(self, name, surname):&nbsp; &nbsp; &nbsp; &nbsp; super().__init__(name)&nbsp; &nbsp; &nbsp; &nbsp; self.surname = surname&nbsp; &nbsp; @Guy.greeting_decorator # <----- here&nbsp; &nbsp; def __str__(self):&nbsp; &nbsp; &nbsp; &nbsp; return f'{self.name} {self.surname}'JohnDoe = GuyWithSurname('John', 'Doe')这样,当你调用print(JohnDoe)它时就会输出Hi, I'm John, fullname: John Doe.请注意,我必须更改greeting_decorator和return_function参数才能正确处理self.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python