Python uses decorator and reports error typeerror: ‘nonetype’ object is not callable ‘

In the process of learning python, write a decorator according to the example of online tutorial https://www.liaoxuefeng.com/wiki/1016959663602400/1017451662295584#0 )Type error: ‘nonetype’ object is not callable ‘

The code is as follows:

1 def log(func) :
2     def wrapper():
3         print('time:')
4         func()
5     return wrapper()
6 @log
7 def show():
8     print('2019')
9 show()

The results of normal operation should be as follows:

time:
2019

After searching around the Internet, they all said that the solution was to remove the “()” in the last function call statement, and there was no other explanation. But I feel that there is a problem, so make a note

After removing, it is found that there is no error, and the result can be displayed normally. But this kind of operation obviously violates our basic common sense of writing code( In addition to the special syntax, there is generally no function that can be called directly only through the function name.)

In fact, from the error message, we can guess that the show function could not be called. After testing with the code, we found that show has indeed become a non type

def log(func) :
    def wrapper():
        print('time:')
        func()
    return wrapper()
@log
def show():
    print('2019')
if show is None:
    print("True")

Results of operation:

time:
2019
True

After the test, we found that not only show has become a non type, but also the operation of calling show has been executed. In fact, according to the writing method in the tutorial, the function call has been completed in the “@ log” statement, and there is no need to call it again. The last line of code is actually redundant. Moreover, this “@ log” writing method also changes the type of the show function“

Putting @ log in the definition of show() function is equivalent to executing a statement:

show= log(show)

”This function cannot be called in the usual way later. I don’t know the specific mechanism yet. Or there’s some other way to repeat the call. It will be added later

if there are any mistakes in the expression or concept in the article, please reply

Similar Posts: