你能解释一下 Python 中的装饰器是什么吗?

Can you explain what a decorator is in Python?

我正在研究 Python OOP,我谈到了装饰器的主题,但是我用来学习的 material 没有深入介绍它。 我post示例代码:

class Duck:
    def __init__(self, **kwargs):
        self.properties = kwargs

    def quack(self):
        print("Quaaack!")

    def walk(self):
        print("Walk like a duck.")

    def get_properties(self):
        return self.properties

    def get_property(self, key):
        return self.properties.get(key, None)

    @property
    def color(self):
        return self.properties.get("color", None)

    @color.setter
    def color(self, c):
        self.properties["color"] = c

    @color.deleter
    def color(self):
        del self.properties["color"]

def main():
    donald = Duck()
    donald.color = "blue"
    print(donald.color)

if __name__ == "__main__": main()

你能帮我理解装饰器的重要性吗? 能简单介绍一下装饰器的概念吗?

上面的代码写一些我能简单说的,

一般说装饰器是

"Function decorators are simply wrappers to existing functions"

装饰器总是包装另一个函数,更不用说装饰器本身就是一个函数

在上面的代码中,您正在设置、获取、删除 property/formally "duck" 的一个属性,它是一种颜色。

装饰器总是以“@”开头。 @property 是一个预定义的装饰器函数,意味着采用 getter、setter 和 class

的 del 函数
    @property #getter
    def color(self):
        return self.properties.get("color", None)

    @color.setter #setter
    def color(self, c):
        self.properties["color"] = c

    @color.deleter #del
    def color(self):
        del self.properties["color"]

您所做的只是将函数(getter,setter,del) 作为参数传递给@属性

如果你写了你的主要部分,它会像

if __name__ == "__main__": main()  
    donald = Duck() //creating object
    donald.color = "blue" //call the setter method, look its more intuitive!!  (you don't using the donald.color("blue") syntax)
    print(donald.color)//getter

我们也可以拥有自己的装饰器,我强烈建议您阅读建议的link以了解其各种用途和优点