Ole*_*kov 6 python class class-decorator
完整代码示例:
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
Run Code Online (Sandbox Code Playgroud)
尝试执行测试时,获取错误:
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'
Run Code Online (Sandbox Code Playgroud)
是否可以从装饰类访问静态字段?
虽然 @martineau 的答案可能更好地解决了您试图解决的具体问题,但更通用的方法可能是使用创建元类来重新定义实例上的实例方法(类是 的实例)。__getattr__typetype
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
Run Code Online (Sandbox Code Playgroud)
这允许通过 传递对类本身的属性查找WrapperMeta.__getattr__。