I have code like this and i want to write decorator which will add decoradted function as class method of class 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!"
What about this approach?
PS The code is not structurally optimized for the sake of clarity
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!"
Is this what You were going for:
class A:
def __init__(self):
pass
@classmethod
def foo(cls):
return "Hello!"
def bar(self):
return "Hello again!"
print(A.foo())
print(A().bar())
read docs here
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'
You need to instantiate MyClass To reach(Call) Instance Method
test = MyClass()
test.method()
You Can directly access class Method without instantiate
MyClass.cls_method()
MyClass.static_method()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.