Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何修饰继承的方法-Python_Python_Decorator_Python Decorators - Fatal编程技术网

如何修饰继承的方法-Python

如何修饰继承的方法-Python,python,decorator,python-decorators,Python,Decorator,Python Decorators,我必须装饰一个继承的方法,但它装饰了所有继承的方法。基本上,我必须创建一个装饰器,只装饰类中的一个方法 测试是这样的 @my_decorator class TestClass(Subclass): pass t = TestClass() t.say_hi class SubClass(): def __init__(self): pass def say_hi(): print("Hi") def say

我必须装饰一个继承的方法,但它装饰了所有继承的方法。基本上,我必须创建一个装饰器,只装饰类中的一个方法

测试是这样的

@my_decorator
    class TestClass(Subclass):
        pass

t = TestClass()
t.say_hi
class SubClass():
    def __init__(self):
        pass

    def say_hi():
        print("Hi")

    def say_wow():
        print("wow")
假设我的子类看起来像这样

@my_decorator
    class TestClass(Subclass):
        pass

t = TestClass()
t.say_hi
class SubClass():
    def __init__(self):
        pass

    def say_hi():
        print("Hi")

    def say_wow():
        print("wow")
现在我必须让我的_decorator,在它打印hi之前,它必须对继承的函数说_hi to print***

我试着这样做,但装饰器适用于子类中的所有方法

当然,它适用于子类的每个函数,但是如何使它只适用于say_hi函数呢-它还返回一个TypeError非类型对象不可调用

首先让我们修复子类,因为实例方法在定义时需要显式的实例参数:

class SubClass():
    def __init__(self):
        pass

    def say_hi(self):
        print("Hi")

    def say_wow(self):
        print("wow")
现在,您希望装饰程序在调用原始方法之前,将say_hi方法替换为打印“**”的方法。让我们写一个这样做的装饰师*:

def my_decorator(cls):
    orig = cls.say_hi          # save the original method
    def say_hi(self):          # define a new one
        print('****')
        return orig(self)      # ... calling the original method
    cls.say_hi = say_hi        # replace the method in the class
    return cls
然后,您可以使用:

@my_decorator
class TestClass(SubClass):
    pass
t = TestClass()
t.say_hi()
并按预期获得:

****
Hi

*这是一个非常简单的decorator,它只能替换say_hiself方法:既不能使用不同的名称,也不能使用其他参数,但decorator可以更加智能…

如果要修饰一个方法,那么就修饰该方法,而不是修饰包含它的类。如果您想要一个新类,那么应用于该类的装饰器需要返回一个类

def print_banner(f):
    def _(*args, **kwargs):
       print("****")
       f(*args, **kwargs)
    return _

class SubClass():
    def __init__(self):
        pass

    @print_banner
    def say_hi(self, ):
        print("Hi")

    def say_wow(self):
        print("wow")

修饰类和修饰该类中的单个方法之间有很大的区别。你展示的装饰器,撇开错误不谈,在调用它的say_hi方法后,看起来它用None替换了SubClass。这就是我不知道怎么做的。我只想装饰你的一种方法。。。修饰方法,而不是类。很抱歉,对python来说是个新手,但我不能修饰方法,因为这些是测试数据,我不能更改它们。非常感谢,它现在工作得非常好。我用python编写的第一个程序让我发疯:然而,我不是装饰类的人,但我得到的测试将在我的程序上运行,它要求我为这个TestClass制作一个装饰器。这是一个练习,否则我只会装饰继承的方法