python-当函数赋给变量时带括号与不带括号的区别

python-当函数赋给变量时带括号与不带括号的区别

参见下面的例子:

def test():
    print("call the test func")
    return 0

p = test
print("type(p): ", type(p))

print('----------------------------------')

p = test()
print("type(p): ", type(p))

# 相当于是给print()函数取了一个别名
p = print
p("oh, oh, oh")

输出:

type(p):  <class 'function'>
p =  <function test at 0x000002BBFF0FA4D0>
----------------------------------
call the test func
type(p):  <class 'int'>
p =  20
oh, oh, oh

结论:

  • 当不带括号的时候相当于是把这个函数对象赋值给变量(注意:并不会真的去执行该函数)
  • 当带括号的时候相当于是把这个函数的返回值赋值给变量(由于要得到返回值,所以会真的执行)
  • 当不带括号的时候将函数赋值给变量,相当于是给该函数新取了一个别名。
posted @ 2022-09-30 14:35  夜行过客  阅读(449)  评论(0编辑  收藏  举报