2014-07-01 33 views
1

參數是有可能追加到一個默認的函數參數或從外部獲取函數參數的值?追加到默認的功能

例如:

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]) 

我不認爲這是一個很好的做法,但我很好奇。

+0

有什麼錯調用'FOO( 「你好」, 「bazbla」)'?你想修改函數本身嗎? – bereal

+0

[獲取函數參數的默認值?]的可能重複(http://stackoverflow.com/questions/12627118/get-a-function-arguments-default-value) –

回答

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

__defaults__屬性 是documented here


所以,改變使用默認值foo的參數,你可以使用字符串格式化:

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