Please what does func() mean in python when used inside a function

邮差的信 提交于 2021-02-07 12:26:40

问题


Please what does func() mean in python when used inside a function,For example in the code below.

def identity_decorator(func):
    def wrapper():
        func()
    return wrapper

回答1:


func is an argument given to the function identity_decorator().

The expression func() means "call the function assigned to the variable func."

The decorator is taking another function as an argument, and returning a new function (defined as wrapper) which executes the given function func when it is run.

Here is some information about decorators.




回答2:


I was wondering the same! You can see how it works with the follow example:

def make_pretty(func):
    def inner():
       print("I got decorated")
       func()
    return inner

def ordinary():
    print("I am ordinary")

pretty = make_pretty(ordinary)
pretty()

Output
I got decorated
I am ordinary 

Now when you remove the func() and you try to rerun it:

def make_pretty(func):
    def inner():
       print("I got decorated")
    return inner

def ordinary():
    print("I am ordinary")

pretty = make_pretty(ordinary)
pretty()

Output
I got decorated

You see the the decorated function was not called. Please have a look here https://www.programiz.com/python-programming/decorator



来源:https://stackoverflow.com/questions/27219439/please-what-does-func-mean-in-python-when-used-inside-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!