Python 类能否写类方法中的类装饰器?
class A: def fun_A(self):
....
def fun_B(self):
...
- 方法
B
怎么使用方法A
作为装饰器呢?
python">class A: def fun_A(self):
....
@A.fun_A
def fun_B(self):
...
- 这样貌似不行,该如何解决
回答:
两种思路:
1.将fun_A定义为一个静态方法,并使用该静态方法作为装饰器。
class A: @staticmethod
def fun_A(func):
...
@fun_A
def fun_B(self):
...
2.将fun_A定义为一个装饰器函数,并在类的外部使用该装饰器对fun_B进行装饰。
def fun_A(func): ...
class A:
@fun_A
def fun_B(self):
...
回答:
class A: some_state = "Hello, world!"
@classmethod
def fun_A(cls, func):
def wrapper(*args, **kwargs):
print("Before calling function")
print("Class state is:", cls.some_state)
result = func(*args, **kwargs)
print("After calling function")
return result
return wrapper
@fun_A
def fun_B(self):
print("Inside function B")
回答:
#!usr/bin/python# *- coding:utf8 -*-
class A:
def __init__(self, name):
self.name = name
def wrapper(func):
def inner(*args, **kwargs):
return func(*args, **kwargs) + " hello!"
return inner
@wrapper
def say_hello(self, lastname):
return self.name + ' ' + lastname
def __call__(self, *args, **kwargs):
return "test"
if __name__ == '__main__':
a = A(name="sampson")
print(a.say_hello("clarence"))
print(a.wrapper()())
建议不要这样做, a.wrapper()()的时候这时候A object必须callable
以上是 Python 类能否写类方法中的类装饰器? 的全部内容, 来源链接: utcz.com/p/938972.html