简体   繁体   English

Python 动态导入类并调用它们的函数

[英]Python dynamically import classes an call their functions

I have one Abstract Animal class.我有一只抽象动物 class。

from abc import ABC, abstractmethod


class Animal(ABC):  # Inherit from ABC(Abstract base class)
    @abstractmethod  # Decorator to define an abstract method
    def feed(self):
        pass

And three classes which Implements it以及实现它的三个类

from Animal import Animal

class Lion(Animal):
   def feed(self):
        print("Feeding a lion with raw meat!")

from Animal import Animal

class Panda(Animal):
    def feed(self):
        print("Feeding a panda with some tasty bamboo!")
from Animal import Animal


class Snake(Animal):
    def feed(self):
        print("Feeding a snake with mice!")

Now I just want to import all classes, which are in the project folder and call the feed function of all classes, when there is a feed function.现在我只想导入项目文件夹中的所有类并调用所有类的提要 function,当有提要 function 时。

from glob import glob
import os

if __name__ == '__main__':
   for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), "*.py")):
       name = os.path.splitext(os.path.basename(file))[0]
       # add package prefix to name, if required
       module = __import__(name)
       try:
            module.feed()
       except Exception as e:
            print(e)

My Problem is now, that I get the errors:我现在的问题是,我得到了错误:

module 'Animal' has no attribute 'feed'模块“动物”没有属性“饲料”

module 'Lion' has no attribute 'feed'模块“狮子”没有属性“饲料”

module 'main' has no attribute 'feed'模块'main'没有属性'feed'

module 'Panda' has no attribute 'feed'模块“熊猫”没有属性“饲料”

module 'Snake' has no attribute 'feed'模块 'Snake' 没有属性 'feed'

Can someone help me with this?有人可以帮我弄这个吗?

I take it your files are called Snake.py , Panda.py etc. If so then you are invoking feed() on the files not the classes.我认为您的文件称为Snake.pyPanda.py等。如果是这样,那么您是在文件而不是类上调用feed() You need to get the modules (which you've done), then get the class and then call the method:您需要获取模块(您已经完成),然后获取 class ,然后调用该方法:

from glob import glob
import os

if __name__ == '__main__':
   for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), "*.py")):
       name = os.path.splitext(os.path.basename(file))[0]
       if name == "Animal" or name == "main":  # avoid main.py and Animal.py
           continue
       # add package prefix to name, if required
       module = __import__(name)
       try:
           # get the class
           cls = getattr(module, name)
           # instantiate the class and call the method
           cls().feed()
       except Exception as e:
            print(e)

Ive also included a safety check to exclude main.py and Animal.py我还包括一项安全检查以排除 main.py 和 Animal.py

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

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