1

I have a written a simple class with an __init__ emulating a switch/case flow:

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

Why is everything being selected? - Here is the output it gives me (run it with ideone):

hello bar

hello haz

None

4

3 回答 3

1

Forgot how Python's evaluation strategy worked, was expecting something lazier… rewrote my code so it now works:

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

于 2013-09-22T16:52:23.313 回答
0

In your init method, you are calling the functions bar and haz and put the result in the dictionary:

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

You probably wanted to write self.bar and self.haz without the parenthesis.

于 2013-09-22T16:56:06.753 回答
0

You have to assign the choice to a variable and then run the variable as a function.

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

Assigned the results of the dictionary lookup to a variable choice then invoking choice() Outputs

hello bar
于 2013-09-22T17:12:30.783 回答