Python: 如何修饰函数以将其更改为 class 方法
Python: How can i decorate function to change it into class method
我有这样的代码,我想编写装饰器,它将添加装饰函数作为 class A 的 class 方法。
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!"
这是你想要的吗:
class A:
def __init__(self):
pass
@classmethod
def foo(cls):
return "Hello!"
def bar(self):
return "Hello again!"
print(A.foo())
print(A().bar())
在此处阅读 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()
您可以直接访问 class 方法而无需实例化
MyClass.cls_method()
MyClass.static_method()
这种方法怎么样?
P.S。为了清晰起见,代码没有进行结构优化
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(_, *args, **kwargs):
return f(*args, **kwargs)
setattr(cls, inner.__name__, 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!"
我有这样的代码,我想编写装饰器,它将添加装饰函数作为 class A 的 class 方法。
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!"
这是你想要的吗:
class A:
def __init__(self):
pass
@classmethod
def foo(cls):
return "Hello!"
def bar(self):
return "Hello again!"
print(A.foo())
print(A().bar())
在此处阅读 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()
您可以直接访问 class 方法而无需实例化
MyClass.cls_method()
MyClass.static_method()
这种方法怎么样?
P.S。为了清晰起见,代码没有进行结构优化
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(_, *args, **kwargs):
return f(*args, **kwargs)
setattr(cls, inner.__name__, 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!"