python:如何修饰函数以将其更改为类方法

zwghvu4y  于 2021-07-13  发布在  Java
关注(0)|答案(3)|浏览(436)

我有这样的代码,我想写装饰将添加decorded函数作为类a的类方法。

  1. class A:
  2. pass
  3. @add_class_method(A)
  4. def foo():
  5. return "Hello!"
  6. @add_instance_method(A)
  7. def bar():
  8. return "Hello again!"
  9. assert A.foo() == "Hello!"
  10. assert A().bar() == "Hello again!"
xzv2uavs

xzv2uavs1#

这种方法怎么样?
p、 为了清晰起见,代码没有进行结构优化

  1. from functools import wraps
  2. class A:
  3. pass
  4. def add_class_method(cls):
  5. def decorator(f):
  6. @wraps(f)
  7. def inner(_, *args,**kwargs):
  8. return f(*args,**kwargs)
  9. setattr(cls, inner.__name__, classmethod(inner))
  10. return f
  11. return decorator
  12. def add_instance_method(cls):
  13. def decorator(f):
  14. @wraps(f)
  15. def inner(_, *args,**kwargs):
  16. return f(*args,**kwargs)
  17. setattr(cls, inner.__name__, inner)
  18. return f
  19. return decorator
  20. @add_class_method(A)
  21. def foo():
  22. return "Hello!"
  23. @add_instance_method(A)
  24. def bar():
  25. return "Hello again!"
  26. assert A.foo() == "Hello!"
  27. assert A().bar() == "Hello again!"
展开查看全部
nfzehxib

nfzehxib2#

这就是你想要的:

  1. class A:
  2. def __init__(self):
  3. pass
  4. @classmethod
  5. def foo(cls):
  6. return "Hello!"
  7. def bar(self):
  8. return "Hello again!"
  9. print(A.foo())
  10. print(A().bar())
k97glaaz

k97glaaz3#

在此处阅读文档

  1. class MyClass:
  2. def method(self):
  3. # instance Method
  4. return 'instance method called', self
  5. @classmethod
  6. def cls_method(cls):
  7. #Classmethod
  8. return 'class method called', cls
  9. @staticmethod
  10. def static_method():
  11. # static method
  12. return 'static method called'

您需要示例化myclass来访问(调用)示例方法

  1. test = MyClass()
  2. test.method()

您可以直接访问类方法,而无需示例化

  1. MyClass.cls_method()
  2. MyClass.static_method()
展开查看全部

相关问题