首页 > 解决方案 > How to instantiate a class given its parent class in Python?

问题描述

I have 3 subclasses and 1 parent class that make the children share a common method.

Example:

    class Animal:
      def communicate():
        pass

    class Dog(Animal):
       def communicate():
           bark()

    class Cat(Animal):
        def communicate():
            meow()

I would like to provide an API that instantiates a cat or a dog based on the received string that will be either "cat" or "dog" and calls .communicate(), but I don't want to write if and elses to check whether I should run Dog() or Cat(). I wonder if it is possible to bark or meow by doing something like: Animal("dog").communicate()

Where "dog" can be a variable.

Or if possible give the child classes some labelling and be able to instantiate them via this label, or even via the own class name.

The ideia is to not have to write conditions Everytime I define new child child classes.

Thanks in advance!

标签: pythonpython-3.x

解决方案


工厂模式是您的解决方案。

此处描述的自动创建类的条件的方法

我可以展示如何应用元类:

class MetaAnimal(type):
    classes = {}

    def __new__(cls, name, bases, dct):
        result = super().__new__(cls, name, bases, dct)
        cls.classes[name.lower()] = result
        return result

    @classmethod
    def get_animal(cls, name):
        return cls.classes.get(name)


class Animal(metaclass=MetaAnimal):
    def communicate(self):
        pass


class Dog(Animal):
    def communicate(self):
        self.bark()

    def bark(self):
        print('Woof')


class Cat(Animal):
    def communicate(self):
        self.meow()

    def meow(self):
        print('Meow')


MetaAnimal.get_animal('cat')().communicate()
MetaAnimal.get_animal('dog')().communicate()

推荐阅读