函数和类也是对象(属于python的一等公民)
python的一等公民的属性
- 赋值给一个变量
- 可以添加到集合对象中
- 可以作为参数传递给函数
- 可以当做函数的返回值
验证可以赋值给一个变量
def f1(name='mace'):
print(name)
my_func = f1
my_func('mace')
class C1:
def __init__(self):
print('jin')
my_class = C1
my_class()
C:\ProgramData\Anaconda3\python.exe D:/python_demo/chapter01/all_is_object.py
mace
jin
Process finished with exit code 0
验证可以添加到集合中
def f1(name='mace'):
print(name)
class C1:
def __init__(self):
print('jin')
lst = []
lst.append(f1)
lst.append(C1)
for l in lst:
print(l())
C:\ProgramData\Anaconda3\python.exe D:/python_demo/chapter01/all_is_object.py
mace
None
jin
<__main__.C1 object at 0x000001ECF7F2B668>
当调用函数f1时,输入了mace
再打印f1的返回值,由于f1没有返回值,因此返回none
调用类同理
验证可以作为参数传递给函数
验证可以当做函数的返回值
def f1(name='mace'):
print(name)
class C1:
def __init__(self):
print('jin')
def print_func():
print('调用了函数')
return f1
my_f1 = print_func()
my_f1('tom')
C:\ProgramData\Anaconda3\python.exe D:/python_demo/chapter01/all_is_object.py
调用了函数
tom
Process finished with exit code 0