📜  在Python中将函数赋值给变量

📅  最后修改于: 2022-05-13 01:54:45.462000             🧑  作者: Mango

在Python中将函数赋值给变量

在本文中,我们将了解如何在Python中将函数分配给变量。在Python中,我们可以将函数分配给变量。使用该变量,我们可以根据需要多次调用该函数。从而提高代码的可重用性。

执行

只需将函数分配给所需的变量,但不使用 (),即仅使用函数名称。如果变量与函数一起分配给括号 (),则 None 将被返回。

语法

def func():
{
..
}

var=func

var()
var()

例子:

Python3
def a():
  print("GFG")
   
# assigning function to a variable
var=a
 
# calling the variable
var()


Python3
# defined function
x = 123
 
def sum():
    x = 98
    print(x)
    print(globals()['x'])
 
 
# drivercode
print(x)
 
# assigning function
z = sum
 
# invoke function
z()
z()


Python3
# function defined
def even_num(a):
    if a % 2 == 0:
        print("even number")
    else:
        print("odd number")
 
 
# drivercode
# assigning function
z = even_num
 
# invoke function with argument
z(67)
z(10)
z(7)


Python3
# function defined
def multiply_num(a):
    b = 40
    r = a*b
    return r
 
 
# drivercode
# assigning function
z = multiply_num
 
# invoke function
print(z(6))
print(z(10))
print(z(100))


输出:

GFG

以下程序将帮助您更好地理解:

示例 1:

蟒蛇3

# defined function
x = 123
 
def sum():
    x = 98
    print(x)
    print(globals()['x'])
 
 
# drivercode
print(x)
 
# assigning function
z = sum
 
# invoke function
z()
z()

输出:

123
98
123
98
123

示例 2:参数化函数

蟒蛇3

# function defined
def even_num(a):
    if a % 2 == 0:
        print("even number")
    else:
        print("odd number")
 
 
# drivercode
# assigning function
z = even_num
 
# invoke function with argument
z(67)
z(10)
z(7)

输出:

odd number
even number
odd number

示例 3:

蟒蛇3

# function defined
def multiply_num(a):
    b = 40
    r = a*b
    return r
 
 
# drivercode
# assigning function
z = multiply_num
 
# invoke function
print(z(6))
print(z(10))
print(z(100))

输出:

240
400
4000