问题描述
我有这样的代码,我想编写装饰器,它将装饰函数添加为类 A 的类方法。
class A:
pass
@add_class_method(A)
def foo():
return "Hello!"
@add_instance_method(A)
def bar():
return "Hello again!"
assert A.foo() == "Hello!"
assert A().bar() == "Hello again!"
解决方法
这种方法怎么样?
附注为了清晰起见,代码没有在结构上进行优化
from functools import wraps
class A:
pass
def add_class_method(cls):
def decorator(f):
@wraps(f)
def inner(_,*args,**kwargs):
return f(*args,**kwargs)
setattr(cls,inner.__name__,classmethod(inner))
return f
return decorator
def add_instance_method(cls):
def decorator(f):
@wraps(f)
def inner(_,inner)
return f
return decorator
@add_class_method(A)
def foo():
return "Hello!"
@add_instance_method(A)
def bar():
return "Hello again!"
assert A.foo() == "Hello!"
assert A().bar() == "Hello again!"
,
这就是你想要的:
This is the incorrect date string format,try again fill the
,
在此处阅读docs
class MyClass:
def method(self):
# instance Method
return 'instance method called',self
@classmethod
def cls_method(cls):
#Classmethod
return 'class method called',cls
@staticmethod
def static_method():
# static method
return 'static method called'
需要实例化 MyClass 才能到达(调用)实例方法
test = MyClass()
test.method()
可以直接访问类Method而无需实例化
MyClass.cls_method()
MyClass.static_method()