Skip to main content
 首页 » 编程设计

python之附加到函数的默认参数

2025年05月04日18xiaohuochai

是否可以附加到默认函数参数或从外部获取函数参数的值?

例如:

def foo(bar, foo="baz"): 
    print(bar, foo) 
 
foo("hello", "world") # print "hello world" 
foo("hello", foo="world") # print "hello world" as well 
foo("hello") # print "hello baz" 
foo("hello", foo<append it>"bla") # how? want to print "hello bazbla" 
print("default value of foo's foo parameter:", [magic here]) 

我不认为这是一个好的做法,但我很好奇。

请您参考如下方法:

>>> foo.__defaults__ 
('baz',) 

__defaults__ 属性 是documented here .


因此,要使用默认值更改 foo 参数,您可以使用字符串格式:

foo("hello", foo="{}bla".format(foo.__defaults__[0]))