使用变量函数调用调用类的函数

时间:2018-04-08 03:00:50

标签: python

我正在尝试从类中调用一个函数,该名称将根据实例化的敌人类型而改变。我怎么能做到这一点?

我的尝试是:AssignClass.[self.Class](self)

但显然sintax毫无意义

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

2 个答案:

答案 0 :(得分:2)

您可以使用getattr()检索类方法,然后只需传递Creature实例,例如:

class Creature:

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

顺便说一下。除了Python类的推荐样式之外,这是一切,其中最重要的是你在Creature中隐藏AssignClass类(首先不应该是类)。我建议你仔细阅读PEP 8 -- Style Guide for Python Code

答案 1 :(得分:0)

再玩一遍,发现我可以使用eval。 (安全,因为这里不能添加用户输入)

class Creature:

    def __init__(self, Name, Class):

        self.Name   = Name
        self.Class  = Class

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