2010-12-10 47 views
1

我希望能够传递额外的参数给一个函数,如果它们存在,然后相应地行动(比如从函数中打印出某些东西),如果这些标志不存在,只需执行函数通常不打印额外信息,我会如何处理这个问题?函数中的可选标志

干杯

回答

7

比方说xyz是需要argruments和opt是可选的:

def f(x, y, z, opt=None): 
    # do required stuff 
    if opt is not None: 
    # do optional stuff 

这可以用三个或四个参数来调用。你明白了。

0
def fextrao(x, y, a=3): 
    print "Got a", a 
    #do stuff 

def fextrad(x, y, **args): 
    # args is a dict here 
    if args.has_key('a'): 
    print "got a" 
    # do stuff here 

def fextrat(x, y, *args): 
    # args is a tuple here 
    if len(args) == 1: 
    print "Got tuple", args[0] 
    #do stuff 

fextrao(1, 2) 
fextrao(1, 2, 4) 
fextrad(1, 2, a=3, b=4) 
fextrat(1, 2, 3, 4) 
0

你可以有默认值给你函数参数,类似于可选参数。事情是这样的:

def myFunction(required, optionalFlag=True): 
    if optionalFlag: 
     # do default 
    else: 
     # do something with optionalFlag 
1

你可以使用还关键字参数:

def f(x, y, **kwargs): 
    if 'debug_output' in kwargs: 
     print 'Debug output' 

然后你可以有你喜欢的尽可能多的..

f(1,2, debug_output=True, file_output=True)