3

In my code I have many if/elif statements like this:

if type == "cat":
    vote = VoteCat (
        user = user,
        cat_id = thing_id )
    vote.save()
elif type == "dog":
    vote = VoteDog (
        user = user,
        dog_id = thing_id )
    vote.save()

What would be a good way to change my code to get rid of the if statements and instantiate the object I need dynamically? The code I am hoping I can write would accomplish the same as above but look more like this:

AnimalVote = get_animalvote_by_type(type)
AnimalVote.user = user
AnimalVote.assign_animal_id(thing_id)
AnimalVote.save()
3
  • 1
    if i'm understanding your question correctly, perhaps the easiest thing to do would be to have an AnimalVote model with a field specifying what type of animal it is. Commented Jan 9, 2013 at 0:11
  • Since you're using django how about a custom objects manager? Commented Jan 9, 2013 at 0:12
  • I've thought doing it your way Kapura but thought that it may not scale as well as I add many different kinds of Animals that have slightly different behaviors. Commented Jan 9, 2013 at 0:28

2 Answers 2

7

The simplest translation is:

types = dict('cat' = CatType, 'dog' = DogType)
newobj = types[type](user = user, cat_id = thing_id)

Obviously, this relies on the types taking the same parameters.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the simple, quick answer. I feel like I should have known I could do it this way.
@tedtoy It's not entirely obvious until you know about it.
3

Classes in Python are objects, so you can just have a map mapping names to classes:

animal_type_map = {'cat': VoteCat, 'dog': VoteDog}

Then you can use animal_type_map[type] just as you would use VoteCat or VoteDog.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.