Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 是否有一个选项可以调用带参数的方法并在该方法中获取默认值?_Python 2.7_Default Value - Fatal编程技术网

Python 2.7 是否有一个选项可以调用带参数的方法并在该方法中获取默认值?

Python 2.7 是否有一个选项可以调用带参数的方法并在该方法中获取默认值?,python-2.7,default-value,Python 2.7,Default Value,我有下一个代码: def foo(i_String, i_TimeOut=10s): """ do some stuff""" if __name__ == __main__: userInput = raw_input("Run with default time? Yes / No ?") time = none if userInput=="Yes" else 5s foo("abc", time) 是否有一种方法可以使用时间参数调用foo方法,但从调

我有下一个代码:

def foo(i_String, i_TimeOut=10s):
    """ do some stuff"""

if __name__ == __main__:
    userInput = raw_input("Run with default time? Yes / No ?")
    time = none if userInput=="Yes" else 5s 
    foo("abc", time)

是否有一种方法可以使用时间参数调用foo方法,但从调用方法而不是传递的参数中获取具有相同签名的默认值i_Timeout(10s)

您可以使用
检查
模块:

import inspect
def get_default_args(func):
    args, varargs, keywords, defaults = inspect.getargspec(func)
    return dict(zip(args[-len(defaults):], defaults))
因此:

def foo(i_String, i_TimeOut=10):
    print i_TimeOut

if __name__ == "__main__":
    userInput = raw_input("Run with default time? Yes / No ?")
    time = get_default_args(foo).values()[0] if userInput=="Yes" else 5 
    foo("abc", time)

>>> if __name__ == "__main__":
...     userInput = raw_input("Run with default time? Yes / No ?")
...     time = get_default_args(foo).values()[0] if userInput=="Yes" else 5 
...     foo("abc", time)
... 
Run with default time? Yes / No ?Yes
10
>>> if __name__ == "__main__":
...     userInput = raw_input("Run with default time? Yes / No ?")
...     time = get_default_args(foo).values()[0] if userInput=="Yes" else 5
...     foo("abc", time)
... 
Run with default time? Yes / No ?No
5
>>>