0

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!"
koliber
  • 23
  • 4

3 Answers3

1

What about this approach?
P.S. 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!"

ekon
  • 443
  • 3
  • 12
  • Thank you <3. Could you just tell me what is this "_" inside inner pls. Sorry for my bad english btw. – koliber Apr 27 '21 at 14:54
  • [This](https://stackoverflow.com/a/5893946/11179620) answer explains it well enough – ekon Apr 27 '21 at 14:57
0

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())
Matiiss
  • 5,970
  • 2
  • 12
  • 29
  • Not really, i have to write code of these two decorators: add_class_method and add_instance_method. This code is just an example of how the result should look like. – koliber Apr 27 '21 at 14:13
0

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()
George Imerlishvili
  • 1,816
  • 2
  • 12
  • 20
  • But my class should be empty at the beginning, and i have to add method foo and bar via these decorators def add_class_method(A): def real_decorator(func): def wrapper(*args,**kwargs): return func(*args, **kwargs) return wrapper() return real_decorator I have passed class to decorator but i dont know how to return it with intended method – koliber Apr 27 '21 at 14:45