[Python04]-函数高级属性

本文介绍了Python中函数的默认参数用法,包括如何处理列表、字典和类作为默认参数,以及如何实现与用户的交互。通过实例展示了如何定义函数接收用户输入并根据输入执行不同操作,同时说明了如何在函数中处理默认参数和抛出错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.函数的默认参数

Python函数支持默认参数。与其他类型的语言的默认参数适用方法相同。

>>>def someFunction(message = "hello"):
	print(message)
>>> someFunction()
hello
>>> someFunction("new message")
new message
>>>

值得注意的是,当默认值是list,dictionary或者class的时候,这样说起来可能不好理解,下面的例子可以说明这个问题

>>> def f(a, L=[]):
	L.append(a)
	return L

>>> print(f(1))
[1]
>>> print(f(2))
[1, 2]
>>> print(f(3))
[1, 2, 3]
>>>

这种情况下,我们经常很困扰,因为与原来我们对默认参数的理解方式不一样,下面的例子可以解决这个问题,使得默认参数的形式看起来跟原来一样。

>>> def f2(a, L=None):
	if L is None:
		L = []
		L.append(a)
		return L
	
>>> print(f2(1))
[1]
>>> print(f2(2))
[2]
>>> print(f2(3))
[3]
>>>

2.函数的交互

函数可以接收用户输入的参数,与用户进行交互。

>>> def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
	while True:
		ok = input(prompt)
		if ok in ('y', 'ye', 'yes'):
			return True
		if ok in ('n', 'no', 'nop', 'nope'):
			return False
		retries = retries - 1
		if retries < 0:
			raise IOError('uncooperative user')
		print(complaint)

		
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?y
True
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?n
False
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?
Yes or no, please!
Do you really want to quit?y
True
>>> ask_ok('Do you really want to quit?')
Do you really want to quit?
Yes or no, please!
Do you really want to quit?
Yes or no, please!
Do you really want to quit?
Yes or no, please!
Do you really want to quit?
Yes or no, please!
Do you really want to quit?
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    ask_ok('Do you really want to quit?')
  File "<pyshell#17>", line 10, in ask_ok
    raise IOError('uncooperative user')
OSError: uncooperative user
>>>

      这里函数接收用户输入的内容,根据输入运行不同的代码段,并且用户可以设定交互的次数及提示的内容,这个例子很好地演示了默认参数及函数交互,并且包含了显式抛出错误的使用方法。

      默认参数如果有多个时,我们需要指定其中某个参数的时候,我们可以参照下面的例子:

>>> def fun(action, type='Move'):
	print(action)
	print(type)
	
>>> fun("Car")
Car
Move
>>> fun("Man","Jump")
Man
Jump
>>> def f(a,b = "b",c = "c"):
	print(a)
	print(b)
	print(c)

	
>>> f("this is a",c = "this is c")
this is a
b
this is c
>>>

3.Lambda表达式的支持

Python有一类函数可以返回Lambda表达式,就像一个函数返回另一个函数。

>>>def make_incrementor(n):
	return lambda x: x + n
</span><span style="font-family:Microsoft YaHei;"><span class="n">f</span> <span class="o">=</span> <span class="n">make_incrementor</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
>>> f(0)
42
>>> f(1)
43

这里返回一个表达式,f 存储了这个表达式,即 f 等同于一个函数:

def fun(x):
	return x + 42



 






 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值