Dylan Grove
Dylan Grove

Reputation: 523

Call function of class using a variable function call

I'm trying to call a function from a Class thats name will change depending on what type of enemy is being instantiated. How can I accomplish this?

My attempt was this: AssignClass.[self.Class](self)

but obviously that sintax makes no sense

class Creature:

    def __init__(self, Name, Class):

        self.Name   = Name
        self.Class  = Class

        # Using a variable function call to remove
        # the need for a ton of 'if' statements

        AssignClass.[self.Class](self)

        # Basically automate doing this:

        if self.Class = "Orc":
            AssignClass.Orc(self)
        elif self.Class = "Wizard"
            AssignClass.Wizard(self)


class AssignClass:

    def Orc(Creature):
        Creature.Class='Orc'
        Creature.Health=100
        Creature.Mana=0

    def Wizard(Creature):
        Creature.Class='Wizard'
        Creature.Health=75
        Creature.Mana=200

Evil_Wizard = Creature("Evil Wizard", "Wizard")

Upvotes: 0

Views: 47

Answers (2)

zwer
zwer

Reputation: 25789

You can retrieve class methods using getattr() and then just pass your Creature instance, e.g.:

class Creature:

    def __init__(self, Name, Class):
        self.Name   = Name
        self.Class  = Class
        getattr(AssignClass, Class)(self)

Btw. this is everything but a recommended style for Python classes, the least of which is that you're shadowing the Creature class in your AssignClass (which shouldn't be a class in the first place). I'd recommend you to read the PEP 8 -- Style Guide for Python Code thoroughly.

Upvotes: 2

Dylan Grove
Dylan Grove

Reputation: 523

Played around a little more and found that I can use eval for this. (Safe as no user input can be added here)

class Creature:

    def __init__(self, Name, Class):

        self.Name   = Name
        self.Class  = Class

        eval('AssignClass.'+Class)(self)

Upvotes: 0

Related Questions