如何使用条件

时间:2018-12-18 15:00:27

标签: python oop

我将向您展示我的脚本,然后解释我想做什么

class Animal(object):
    def __init__(self,name=None):
        self.name=name
        if name=="dog":
            object=Dog()
        if name=="cat":
            object=Cat()
    def execute(self):
        print("I am animal")

class Dog:
    def __init__(self):
        pass
    def execute(self):
        print("I am a dog")

class Cat:
    def __init__(self):
        pass
    def execute(self):
        print("I am a cat")


if __name__ =="__main__":
    instanceAnimal=Animal("cat") # I would like to get "I am a cat" but I got "I am animal"
    instanceAnimal.execute()

我知道这不是固有的好方法,但是我有一个用例,我想实例化一个Animal实例,并在输入中指定一个名称,该类将调用相应的execute。

希望我的例子很清楚

3 个答案:

答案 0 :(得分:2)

使用元类和继承的干净解决方案:

class AnimalType(type):
    _classes = {}

    def __init__(cls, name, attribs, bases):
        super(AnimalType, cls).__init__(name, attribs, bases)
        cls._classes[name.lower()] = cls


class Animal(object):
    __metaclass__ = AnimalType

    def __new__(cls, name=None):
        newcls = type(cls)._classes.get(name, Animal)
        return object.__new__(newcls, name)

    def __init__(self, name=None):
        self.name = name

    def execute(self):
        print("I am animal")


class Dog(Animal):
    def execute(self):
        print("I am a dog")


class Cat(Animal):
    def execute(self):
        print("I am a cat")

如果您根本不想继承,只需使用工厂函数即可:

class Animal(object):
    def execute(self):
        print("I am animal")

class Dog:
    def execute(self):
        print("I am a dog")

class Cat:
    def execute(self):
        print("I am a cat")


_clsmap = {
   "animal": Animal,
   "dog": Dog,
   "cat": Cat
   }

def make_animal(name):
    return _clsmap.get(name, Animal)()

答案 1 :(得分:1)

尽管继承是最佳解决方案,但OP专门要求其他解决方案

object = Dog()object = Cat()无用。它将DogCat实例分配给局部变量object,仅此而已。它不会将其绑定到任何东西。

您将必须在Animal中保留对其的引用,并将Animal.execute绑定到适当的execute方法。

此外,您可以使用字典使初始化更加简洁:

class Dog:
    def execute(self):
        print("I am a dog")

class Cat:
    def execute(self):
        print("I am a cat")

class Animal(object):
    names_to_classes = {'dog': Dog, 'cat': Cat}

    def __init__(self, name=None):
        self.name = name
        try:
            self.object = self.names_to_classes[name]()
        except KeyError:
            raise TypeError('name must be either "dog" or "cat"')

    def execute(self):
        self.object.execute()


instanceAnimal = Animal("cat")
instanceAnimal.execute()
instanceAnimal = Animal("dog")
instanceAnimal.execute()
instanceAnimal = Animal("penguin")
instanceAnimal.execute()

输出

I am a cat
I am a dog
TypeError: name must be either "dog" or "cat"

此方法的缺点在于,Dog.__init__Cat.__init__应该接受相同的参数。

答案 2 :(得分:0)

这是您实现所需目标的方法:

&