E
E
ekolodenets2020-07-05 12:05:29
Python
ekolodenets, 2020-07-05 12:05:29

Python. Why does the decorator in the class not work?

It's just how the code works.

def typed(func):
    def wrapper(*args):
        print("in decor")
        return func(*args)
    return wrapper

@typed
def add(a: int, b: int) -> str:
    return a + b

if __name__ == '__main__':

    a = 4
    b = 2
    result = add(a, b)
    print(result)

As soon as I insert it into the class, it gives an error:
TypeError: add() takes 2 positional arguments but 3 were given
class MyClass:
    def typed(func):
        def wrapper(*args):
            print("in decor")
            return func(*args)
        return wrapper

    @typed
    def add(a: int, b: int) -> str:
        return a + b

if __name__ == '__main__':

    a = 4
    b = 2
    result = MyClass().add(a, b)
    print(result)

Though everything stays the same

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2020-07-05
@ekolodenets

def add(self, a: int, b: int) -> str:

A
Alexander, 2020-07-05
@NeiroNx

in a class, the first argument is the current instance of the class. Any function. Always.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question