在Python中,引用自定义函数可以通过以下几种方法:
直接使用函数名
```python
def my_function():
print("Hello, world!")
my_function() 调用自定义函数
将函数赋值给变量
```python
def my_function():
print("Hello, world!")
add_reference = my_function
add_reference() 调用自定义函数
使用lambda表达式创建匿名函数引用 (如果需要简洁的函数):
```python
add_reference = lambda a, b: a + b
result = add_reference(2, 3) 调用自定义函数
从其他模块导入函数(如果函数定义在另一个模块中):
```python
from my_module import my_function
my_function() 调用自定义函数
使用`from ... import *`导入所有函数(谨慎使用,可能会导致命名冲突):
```python
from my_module import *
my_function() 调用自定义函数
在大型程序中,通过修改`sys.path`来导入其他模块中的函数```python
import sys
sys.path.append('subfunction') 添加路径到模块搜索路径
from fun import * 从fun模块导入所有函数
x = 1
y = 2
a = add(x, y) 调用自定义函数