Python编程进阶:函数与类的深度探索
1. 函数参数传递
在Python中,向函数传递参数有多种方式。你既可以直接传递列表,也可以传递包含列表的变量名。例如:
names = ['Schrepfer', 'Maier', 'Santiago', 'Adams']
alphabetize(names)
这个函数会将传入的名字按字母顺序显示出来,结果如下:
Adams, Maier, Santiago, Schrepfer
除了传递列表,你还可以设计函数使其接受任意数量的参数。使用 *args 作为参数名即可实现这一功能,示例代码如下:
def sorter(*args):
""" Pass in any number of arguments separated by commas
Inside the function, they treated as a tuple named args """
# Create a list from the passed-in tuple
newlist = list(args)
# Sort and show the list.
newlist.sort()
print(newlist)
在函数内部,传入的参数会被当作一个名为 <
超级会员免费看
订阅专栏 解锁全文
1257

被折叠的 条评论
为什么被折叠?



