关键字参数默认为您在函数定义中提供的参数。
def some_method(param1="param1", param2=None):
# param1 is "param1" unless some other value is passed in.
# param2 is None if some value is not passed for it.
考虑:
def print_values(first_value="Hello", second_value=None):
print first_value, second_value or "World!"
print_values() #prints Hello World!
print_values(first_value="Greetings") #prints Greetings World!
print_values(second_value="You!") # prints Hello You!
print_values(first_value="Greetings", second_value="You!")
# prints Greetings You!
如果要打印局部变量的值,可以通过在定义中添加预期的变量名称来实现:
print first_value, special_variable_name or second_value or "World!"
那么,如果你用那个名字定义一个变量:
special_variable_name = "Sean"
print_values() # prints Hello Sean
但不要这样做——这是出乎意料的、神奇的,而且绝对非 Pythonic——而是将你需要的值作为第二个参数传入。
如果您需要能够使用该变量调用它而不会出错,请确保在模块顶部定义该变量。
special_variable_name = None
# ... much code later ...
special_variable_name = "Sean" #This can be commented out
print_values(second_value=special_variable_name) # prints Hello Sean