简体   繁体   English

Python - 迭代扩展类的类列表?

[英]Python - Iterate through list of classes that extend class?

I have a certain class, namely Animal , and several subclasses like Dog , Cow , Lion , etc. 我有一个类,即Animal ,还有几个子类,如DogCowLion等。

Animal is an abstract class which has an abstract static method eats(Food f) . Animal是一个抽象类,它有一个抽象的静态方法eats(Food f)

All of these subclasses implement eats and, according to each animal, will either return True or False . 所有这些子类都实现了eats ,根据每只动物,它们将返回TrueFalse

How can I iterate through each of those and create a new Animal whose type eats that specific food without manually typing each class? 我如何迭代每一个并创建一个新的Animal其类型eats特定食物而无需手动输入每个类?

For example, I'd like to get an object of type Animal that eats grass, without actually creating a new Cow . 例如,我想得到一个类型为Animal的物体吃草,而不是真正创造一个新的Cow

Finding the subclasses of Animal may be one part, but I am more interested in actually iterating some sort of list of classes and running eats on each of them, until I find one that returns True and then create a new object of that class. 查找Animal的子类可能是其中的一部分,但我更感兴趣的是实际迭代某些类列表并在每个类上运行eats ,直到找到一个返回True然后创建该类的新对象。

Thanks. 谢谢。

You could iterate over all subclasses, do the checks and then get the first one which matches: 您可以遍历所有子类,执行检查,然后获取匹配的第一个:

def create_animal_eating(food):
    gen = (subclass for subclass in Animal.__subclasses__() if subclass.eats(food))
    subclass = next(gen, None)
    if subclass is None:
        raise ValueError("No animal eats " + repr(food))
    new_obj = subclass()

This essentially does exactly what you describe and thus doesn't need any explanation. 这基本上完全符合您的描述,因此不需要任何解释。

But it gets only the immediate subclasses; 但它只获得直接的子类; if you really need all subclasses no matter how deep they are nested, refer to the linked article. 如果您确实需要所有子类,无论它们嵌套的深度如何,请参阅链接的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM