Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.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 - Fatal编程技术网

python中的绑定函数和修饰符

python中的绑定函数和修饰符,python,decorator,Python,Decorator,我正在尝试不同的方法来理解Python中的装饰器和函数。 以下代码是否正确: import math def calculate_area(func): def area(a,b): return a+b return area class Donut(): def __init__(self, outer, inner): self.inner = inner self.outer = outer @calcu

我正在尝试不同的方法来理解Python中的装饰器和函数。 以下代码是否正确:

import math
def calculate_area(func):
    def area(a,b):
        return a+b
    return area

class Donut():
    def __init__(self, outer, inner):
        self.inner = inner
        self.outer = outer

    @calculate_area
    @staticmethod
    def area(self):
        outer, inner = self.radius, self.inner
        return Circle(outer).area() - Circle(inner).area()
“staticmenthod”装饰器会告诉内置的默认元类类型(类的类,参见这个问题)不要创建绑定方法吗? 是否有可能做到:

Donut.area(4,5)
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
Donut.area(4,5)
TypeError: unbound method area() must be called with Donut instance as first argument      (got int instance instead)
Donut.面积(4,5)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
甜甜圈面积(4,5)
TypeError:必须使用Donut实例作为第一个参数调用unbound method area()(改为使用int实例)

请帮助我理解绑定方法和未绑定方法以及decorator对它们的影响。

只需将@staticmethod与decorator交换即可

import math
def calculate_area(func):
    def _area(a, b):
        return a + b
    return _area

class Donut():
    def __init__(self, outer, inner):
        self.inner = inner
        self.outer = outer

    @staticmethod
    @calculate_area
    def area(cls):
        outer, inner = self.radius, self.inner
        return ""
编辑1:

python解释器需要在另一个decorators之前添加@staticmethod at,因为在创建类类型之前,它需要确定类成员和实例成员。如果您的第一个decorator是其他任何东西,解释器将此函数称为实例成员。看

编辑2:


建议使用@classmethod而不是@staticmethod,有关更多信息,请参见

解释为什么此方法有效,而OP的代码无效。感谢回复并让我理解。我只有一个问题:u in u area()是否有特定的含义?在python标准命名约定中,我们添加了一个下划线来指定受保护的成员,对于私有成员,使用u(双下划线)。