python 定义method_Python定义参数数量可变的method的问题

本文详细介绍了Python中定义方法时如何处理可变参数,包括默认参数值、任意参数列表(*args)和关键字参数(**kwargs)。通过示例展示了它们的工作原理,以及在不同场景下的适用性。
摘要由CSDN通过智能技术生成

根据文档(https://docs.python.org/2/tutorial/controlflow.html#more-on-defining-functions)

介绍了三种方法

1 Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow

比较简单,就是给每个method中的参数赋一个默认值

The default values are evaluated(赋值) at the point of function definition in the defining scope, so that

i = 5

def f(arg=i):printarg

i= 6f()

will print 5.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):

L.append(a)returnLprint f(1)print f(2)print f(3)

this will print:

[1]

[1, 2]

[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:

def f(a, L=None):if L isNone:

L=[]

L.append(a)return L

2 Arbitrary Argument Lists

使用*args的时候,将传入的参数pack成tuple来处理:

def foo(*args):for a inargs:printaprint 'end of call'lst= [1,2,3]

foo(lst)

foo(*lst)#output:

[1, 2, 3]

end of call1

2

3end of call

3 Keyword Arguments

使用**kw的时候,将传入的所有的keyword arguments来pack成dict处理:

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter.

对这句话的解释:

def bar(name='Jack', age=21, **kw):printkw

bar(a=1, b=2) # {'a': 1, 'b': 2}

bar(name='Lucy', job='doctor') # {'job': 'doctor'}

*args/**kwargs has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones.

Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as sum() and str.join() do, it might make more sense to leave out the *syntax.

关于 Unpacking Argument Lists的解释:

The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring separate positional arguments.

举例:

>>> range(3, 6) #normal call with separate arguments

[3, 4, 5]>>> args = [3, 6]>>> range(*args) #call with arguments unpacked from a list

[3, 4, 5]

In the same fashion, dictionaries can deliver keyword arguments with the **-operator:

>>> def parrot(voltage, state='a stiff', action='voom'):

...print "-- This parrot wouldn't", action,

...print "if you put", voltage, "volts through it.",

...print "E's", state, "!"...>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}>>> parrot(**d)-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin'demised !

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值