python - 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!
解决方案
工厂模式是您的解决方案。
此处描述的自动创建类的条件的方法
我可以展示如何应用元类:
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()
推荐阅读
- javascript - 有没有办法可以从节点 js 中的 html 属性读取和更新值?
- unity3d - JoinRoom 和 OpJoinRoom 有什么区别?
- python - Dash Plotly 回调输入(页面加载更新)
- xamarin - 没有 iframe 的 Youtube 全屏
- vba - 如何从 VBA 显示 Windows 10 通知 toast
- sql - SQL:如何检查一个表的行是否不存在于另一个表中?
- regex - 如何使用 Goggle 电子表格中的 REGEXMATCH 函数匹配带有 3 个斜杠的 url
- python - 无法对 Python Jupyter Notebook 中的嵌套 for 循环函数使用多重处理
- office365 - Postfix 本地 Office 365 连接器设置
- angular - Angular-如何跳过表单元素之一的值更改