具有继承性的Python静态方法装饰器

问题描述 投票:0回答:2

我的案子:

class BaseClass:

    @staticmethod
    def dummy_decorator(fnc):
        def wrapper():
            print('Im so dummy')
        return wrapper


class InheritedClass(BaseClass):
    def __init__(self):
        pass

    def anymethod(self):
        print('hello world')

[当我看dir()时,我看到了我的静态方法

>>> c = InheritedClass()
>>> dir(c)
['__doc__', '__init__', '__module__', 'anymethod', 'dummy_decorator']

此外,我可以在新类中将虚拟运算符用作简单的static方法。但是,当我尝试将其用作装饰器时,出现错误

class InheritedClass(BaseClass):
    def __init__(self):
        pass

    @dummy_decorator
    def anymethod(self):
        print('hello world')

>>> NameError: name 'dummy_decorator' is not defined

为什么会这样?我知道,如果我将@dummy_decorator更改为@BaseClass.dummy_decorator,那么一切都会正常,但是为什么我不能在没有引用父类的情况下使用装饰器?

python oop inheritance decorator static-methods
2个回答
0
投票
之所以如此,是因为它是一个静态方法,当您输入@BaseClass.dummy_decorator时,它属于您所知道的类,它可以工作。

这是类的属性,因此,除非您将其移出类或将其保存到全局名称空间中,否则您不能仅通过dummy_decorator引用它。>


0
投票
为了正确理解这一点,您需要了解class定义的工作方式。简而言之,class块中的所有内容都像常规的Python代码一样执行。然后,在该class块内创建的每个

name

© www.soinside.com 2019 - 2024. All rights reserved.