简体   繁体   中英

Decorator Beginner __name__ is causing Type error

I have tried a few things to see if it had to do with when the functions were defined but to no avail I could not solve this. I am 90% sure the " name " method is causing the issue. But to me, this seems like it would be a good way to use a wrapper? Trying to explore wrapper because I am currently learning flask and they use wrappers off the get go with subdirectories. Thank you in advanced.

def smartCalc(func):
    def inner(a, b):
        if func.__name__ == "divide":
            print("I am going to divide" + str(a) + "and" + str(b))
            if b == 0:
                print("whoops! cannot divide")
                return
            return func(a, b)
        
        if func.__name__ == "Add":
            print("I am going to add", a, "and", b)
            return func(a, b)
        return inner



@smartCalc
def divide(a, b):
    print(a/b)

@smartCalc
def Add(a, b):
    print(a+b)



Add(3,1)

TypeError: 'NoneType' object is not callable I was somewhat following this when I wanted to try something.

You need to unindent the return inner , and execute func in all cases finally

def smartCalc(func):
    def inner(a, b):
        if func.__name__ == "divide":
            print("I am going to divide", a, "and", b)
            if b == 0:
                print("whoops! cannot divide")
                return
        if func.__name__ == "Add":
            print("I am going to add", a, "and", b)

        return func(a, b)

    return inner

Your smartCalc defines an inner function, and then doesn't do anything else. It doesn't call the inner function, nor does it return something. So it always returns None.

Remember how

@smartCalc
def Add(a, b):
    print(a+b)

is just a fancy way of writing

def Add(a, b):
    print(a+b)
Add = smartCalc(Add)

? Well, now Add is None , so you can't call it anymore.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM