jeudi 28 janvier 2016

Long elif chains vs dictionary with exec()

I am a novice to python and I have read a lot of tutorials on how to properly code. One thing that keep popping up is to never write the same line of code multiple times. I am unsure if long elif arguments count for that, but to me it just looks like bad code.

for exaple:

class answers(object):
    def __init__(self):
        self.x = 'hello world'

    def knight(self):
        print('Neee!')
    def bunny(self):
        print('Rawwww!')
    def pesant(self):
        print('Witch!')
    def dingo(self):
        print('Bad, wicked, naughty Zoot!')
foo = answers()    
egg = input("Sounds:")

if egg == "knight":
    foo.knight()
elif egg == 'bunny':
    foo.bunny()
elif egg == 'pesant':
    foo.pesant()
elif egg == 'dingo':
    foo.dingo()
else:
    print("I don't know?")

That works but I think the following code is looks cleaner.

class answers(object):
    def __init__(self):
        self.x = 'hello world'

    def knight(self):
        print('Neee!')
    def bunny(self):
        print('Rawwww!')
    def pesant(self):
        print('Witch!')
    def dingo(self):
        print('Bad, wicked, naughty Zoot!')

foo = answers()
responce = {'knight': 'foo.knight()', 'bunny': 'foo.bunny()', 'pesant': 'foo.pesant()', 'dingo': 'foo.dingo()'}

while True:
    try:
        egg = input('sounds:')
        exec(responce[egg])
    except KeyError:
        print("I don't know")

Both lines of code do the same thing, does it really matter which I use or is one better then the other?

side note, I know that exec() should not normally be used but I could not find another way to assign a function to a string.

Aucun commentaire:

Enregistrer un commentaire