从修饰类访问静态字段

2024-04-28 02:34:13 发布

您现在位置:Python中文网/ 问答频道 /正文

完整代码示例:

def decorator(class_):
    class Wrapper:
        def __init__(self, *args, **kwargs):
            self.instance = class_(*args, **kwargs)

        @classmethod
        def __getattr__(cls, attr):
            return getattr(class_, attr)
    return Wrapper


@decorator
class ClassTest:

    static_var = "some value"


class TestSomething:

    def test_decorator(self):
        print(ClassTest.static_var)
        assert True

尝试执行测试时,出现以下错误:

test/test_Framework.py F
test/test_Framework.py:37 (TestSomething.test_decorator)
self = <test_Framework.TestSomething object at 0x10ce3ceb8>

    def test_decorator(self):
>       print(ClassTest.static_var)
E       AttributeError: type object 'Wrapper' has no attribute 'static_var'

是否可以从修饰类访问静态字段?你知道吗


Tags: testselfvardefargsstaticdecoratorframework
2条回答

虽然@martineau的答案可能更好地解决了您试图解决的特定问题,但更通用的方法可能是使用创建元类,以便在type实例上重新定义实例方法__getattr__(类是type的实例)。你知道吗

def decorator(class_):
    class WrapperMeta(type):
        def __getattr__(self, attr):
            return getattr(class_, attr)

    class Wrapper(metaclass=WrapperMeta):
        def __init__(self, *args, **kwargs):
            self.instance = class_(*args, **kwargs)

    return Wrapper

这允许通过WrapperMeta.__getattr__传递类本身的属性查找。你知道吗

您可以让decorator创建一个从被修饰的类派生的类。你知道吗

我的意思是:

def decorator(class_):
    class Wrapper(class_):
        def __init__(self, *args, **kwargs):
            self.instance = super().__init__(*args, **kwargs)

    return Wrapper

@decorator
class ClassTest:
    static_var = "some value"

print(ClassTest.static_var)  # -> some value

相关问题 更多 >