python函数二
- 函数传参时,传递的是内存地址
- 参数传递不需另外开辟空间,节省内存
素,只能重新赋值
def my_function(data):
print(data, id(data))
v1 = "武大"
print(id(v1))
my_function(v1)
3.不可变类型,如元组、字符串,无法修改内部元素,参数重新开辟变量空间
def my_function(data):
data = "enya"
print(id(data))
v1 = "武大"
print(id(v1))
my_function(v1)
copy拷贝形实参指向地址不同
import copy
def my_function(data):
data.append(999)
var1 = [11, 22, 33]
new_var1 = copy.deepcopy(var1)
my_function(new_var1)
函数参数有默认值
def my_function(a1,a2=[3,4]):
a2.append(77)
print(a1,a2)
my_function(88)
my_function(55)
my_function(22,[55,66])
my_function(999)
函数返回值也是地址
def my_function(v1, v2=[3, 4]):
v2.append(v1)
return v2
a1 = my_function(8)
print(a1)
a2 = my_function(9)
print(a2)
a3 = my_function(20, [5, 6])
print(a3)
a4 = my_function(10)
print(a4)
*位置传参,**关键字传参
def my_function(*args,**kwargs):
print(args,kwargs)
my_function( [1,2,3], {"aa":1,"bb":2} )
my_function( *[1,2,3], **{"aa":1,"bb":2} )
v1 = "名字是{},身高:{}。".format("武大",18)
v2 = "名字是{name},身高:{height}。".format(name="武大",height=18)
v3 = "名字是{},身高:{}。".format(*["武大",18])
v4 = "名字是{name},身高:{height}。".format(**{"name":"武大","height":18})
函数名
- 函数名也是一个变量,可以当参数传递,可被哈希,函数名可以当做集合的元素、字典的键
def my_function():
return "武大"
my_list = ["张三", "my_function", my_function , my_function() ]
print( my_list[0] )
print( my_list[1] )
print( my_list[2] )
print( my_list[3] )
my_list[2]()
函数当元素放字典中
def eat():
pass
def clothing():
pass
def eat():
pass
def dwelling():
pass
def commute():
pass
def others():
pass
dic_function = {
"1": eat,
"2": clothing,
"3": dwelling,
"4": commute,
"5": others
}
print("欢迎使用小七咨询服务")
print("请选择:1.吃;2.穿;3.住;4.行")
select = input("输入选择的序号")
my_func = dic_function.get(select)
if not func:
print("输入错误")
else:
my_func()
def eat(rice, apple):
pass
def clothing(head, body, shoe):
pass
def play(game1, game2):
pass
func_list = [
{"nickname": eat, "params": {'rice': "泰国小米", "apple": "山西苹果"}},
{"nickname": clothing, "params": {'head': "紫盔", "body": "大衣", "shoe": "靴"}},
{"nickname": play, "params": {'game1': "打枪", 'game2': "打炮"}},
]
for item in func_list:
func = item['nickname']
param_dict = item['params']
func(**param_dict)
- 函数可以当参数,也可以当返回值
- python中以函数为作用域
def my_function():
for num in range(8):
print(num)
print(num)
if 1 == 1:
aa = "admin"
print(aa)
print(aa)
if 1 > 2:
bb = 10
print(bb)
print(bb)
|