Python字典查找返回多个结果?

Python字典查找返回多个结果?,python,python-2.7,dictionary,initialization,switch-statement,Python,Python 2.7,Dictionary,Initialization,Switch Statement,我编写了一个简单的类,其中包含一个模拟开关/案例流的\uuuu init\uuuuu: 类Foo(对象): def bar(自): 打印“hello bar” def haz(自身): 打印“你好,哈兹” def nothing(自我): 打印“无” 定义初始化(self,选择我): {'foo':self.bar(), “can”:self.haz() }.get(选择我,self.nothing()) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': F

我编写了一个简单的
,其中包含一个模拟开关/案例流的
\uuuu init\uuuuu

类Foo(对象):
def bar(自):
打印“hello bar”
def haz(自身):
打印“你好,哈兹”
def nothing(自我):
打印“无”
定义初始化(self,选择我):
{'foo':self.bar(),
“can”:self.haz()
}.get(选择我,self.nothing())
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
Foo(‘Foo’)
为什么所有的东西都被选中了这是它给我的输出():

你好吧

哈兹你好

没有


忘了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')

忘记了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')

在init方法中,调用函数
bar
haz
,并将结果放入字典:

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

您可能想在不带括号的情况下编写
self.bar
self.haz

在init方法中,调用函数
bar
haz
,并将结果放入字典:

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

您可能希望编写不带括号的
self.bar
self.haz

您必须将选项分配给变量,然后将变量作为函数运行

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')
将字典查找的结果分配给变量选项,然后调用choice() 输出


您必须将该选项分配给一个变量,然后将该变量作为函数运行

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')
将字典查找的结果分配给变量选项,然后调用choice() 输出


或者你可以在字典的末尾添加
()
(如我的答案中)…或者你可以在字典的末尾添加
()
(如我的答案中)…