0

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")
0

2 Answers 2

2

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.

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

1 Comment

I've been putting off actually learning PEP 8 for long enough I guess. I just program for fun so nothing I do matters anyways haha. Thank you for the answer.
0

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)

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.