1

我有一個寫了一個簡單class__init__模擬開關/箱流量:Python字典查找返回多個結果?

class Foo(object): 
    def bar(self): 
     print "hello bar" 

    def haz(self): 
     print "hello haz" 

    def nothing(self): 
     print "None" 

    def __init__(self, choose_me): 
     {'foo': self.bar(), 
     'can': self.haz() 
     }.get(choose_me, self.nothing()) 

if __name__ == '__main__': 
    Foo('foo') 

爲什麼一切都被選中? - 這是它給我的輸出(run it with ideone):

招呼吧

你好HAZ

回答

1

忘記Python的評估策略是如何工作的,期待什麼懶...重寫了我的代碼現在可以工作:

class Foo: 
    def bar(self): 
     print "hello bar" 

    def haz(self): 
     print "hello haz" 

    def nothing(self): 
     print "None" 

    def __init__(self, choose_me): 
     {'foo': self.bar, 
     'can': self.haz 
     }.get(choose_me, self.nothing)() 

if __name__ == '__main__': 
    Foo('foo') 

http://ideone.com/kAH5sk

0

在你的init方法,您呼叫的功能barhaz並把結果在詞典:

{ 
'foo': self.bar(), 
'can': self.haz() 
} 

你可能想寫self.barself.haz沒有括號。

0

您必須將選擇分配給一個變量,然後將該變量作爲函數運行。

class Foo(object): 
    def bar(self): 
     print "hello bar" 

    def haz(self): 
     print "hello haz" 

    def nothing(self): 
     print "None" 

    def __init__(self, choose_me): 
     choice = {'foo': self.bar, 
     'can': self.haz 
     }.get(choose_me, self.nothing) 
     choice() 

if __name__ == '__main__': 
    Foo('foo') 

分配字典查找的結果給一個變量的選擇,則調用選擇() 輸出

hello bar 
+0

或者,你可以添加'()'在字典的末尾(就像我的回答)... –