简体   繁体   中英

Python simple decorator issue

def my_decorator(some_function):
        print("Something is happening before some_function() is called.")
        some_function()
        print("Something is happening after some_function() is called.")

def just_some_function():
    print("Wheee!")

just_some_function = my_decorator(just_some_function)
just_some_function()

TypeError: 'NoneType' object is not callable 

I really do not understand, why doesnt this work?

just_some_function should become basically this according to my understanding:

just_some_function():
        print("Something is happening before some_function() is called.")  
        print("Wheee!")  
        print("Something is happening after some_function() is called.")  

But the origional function needs a wrapper function for it to work, eg:

def my_decorator(some_function):
    def wrapper():
        print("Something is happening before some_function() is called.")
        some_function()
        print("Something is happening after some_function() is called.")
    return wrapper

Why? Could someone explain the logic behind it please?

Decorator should create new function that "replace" original function.

def my_decorator(some_function):
        print("Something is happening before some_function() is called.")
        some_function()
        print("Something is happening after some_function() is called.")

This "decorator" return None -> just_some_function = None -> TypeError: 'NoneType' object is not callable

def my_decorator(some_function):
    def wrapper():
        print("Something is happening before some_function() is called.")
        some_function()
        print("Something is happening after some_function() is called.")
    return wrapper

This "decorator" return wrapper -> just_some_function = wrapper -> It's work.

You also can check. Try print(just_some_function.__name__) -> "wrapper".

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