问题: 我想通过装饰器获得类的属性,但它不能。 问题是怎么办?
class DecoratorClass:
def __call__(self, fn, *args, **kwargs) -> Callable:
try:
# do something with the TestClass value
return fn
finally:
pass
class TestClass:
def __init__(self):
self.value = 1
@DecoratorClass()
def bar(self):
return 1
如何通过DecoratorClass达到TestClass的值attr?
答案 0 :(得分:1)
我找到了解决方案:)
class Decoratorclass:
def __call__(self, fn, *args, **kwargs) -> Callable:
def decorated(instance):
try:
# do something with the TestClass value
print(instance.value)
return fn(instance)
finally:
pass
return decorated
class TestClass:
def __init__(self):
self.value = 1
@Decoratorclass()
def bar(self):
return 1