函数
定义方法,给参数name指定默认值,当此参数未赋值时,会默认为cat
def play(user, name=‘cat’):
print(f"\n{user} like play with {name}")
play(‘lvzhuocheng’, ‘dog’)
可以调换参数顺序,但需要指定名字
play(name=‘dog’, user=‘lvzhuocheng’)
禁止函数修改列表(unprinted_designs循环后元素会减少,如何保证unprinted_designs不改变?)
unprinted_designs = [‘phone’, ‘robot’, ‘dodecahedron’]
completed_designs = []
def print_models(unprinted_designs, completed_designs):
while unprinted_designs:
current_design = unprinted_designs.pop()
completed_designs.append(current_design)
假如想禁止其被修改,使用unprinted_designs 的副本
print_models(unprinted_designs[:], completed_designs)
传递任意数量的实参
def make_pizza(*toppings):
print(toppings)
make_pizza(‘pepperoni’)
make_pizza(‘pepperoni’, ‘mushrooms’)
形参与实参相结合
def make_pizza_args(size, *toppings):
print(toppings)
make_pizza_args(1, ‘pepperoni’)
make_pizza_args(2, ‘pepperoni’, ‘mushrooms’)
导入文件,假如要使用base.py中的某个方法
import base
base.function(arg1, arg2)
只导入特定函数
from base import function1, function2
起别名 as,导入模块同理
from base import function1 as fun1, function2 as fun2
导入模块中所有
from base import *