Python:AttributeError:'module'对象没有属性'append'

1 python

我正在尝试创建一个引擎,该引擎以如下格式获取其中包含python文件和函数的文件的内容:

lib1 func1 func2 func3
lib2 func4
Run Code Online (Sandbox Code Playgroud)

我用两个python文件和三个函数设置了一个测试,但我用来导入库和函数的代码不起作用:

class engine (object):
    def __init__ (self, sceneFile):
        # gets contents of sceneFile, then closes
        scenes         = open (sceneFile, 'r')
        lines = scenes.readlines ()
        scenes.close ()
        self.libs = []

        # finds functions and libraries
        for i in range (len (lines)):
            lineContents = lines[i].split()
            self.libs.append (importlib.import_module (lineContents[0]))  # libraries in sceneFile
            for j in range (len (lineContents) - 1):
                self.libs[i].append (lineContents[j + 1])          # functions in sceneFile

    def start (self, nextScene):
        # finds function and library, imports
        for i in range (len (self.libs)):
            for j in range (len (self.libs[i])):
                if self.libs[i][j] == nextScene:
                    nextScene = getattr (self.libs[i], self.libs[i][j])
                    self.start (nextScene)
Run Code Online (Sandbox Code Playgroud)

当我尝试使用测试程序运行时,会弹出以下错误:

Traceback (most recent call last):
  File "ugsE.py", line 32, in <module>
    Engine = engine ("ugsEtest.txt")
  File "ugsE.py", line 21, in __init__
    self.libs[i].append (lineContents[j + 1])          # functions in sceneFile
AttributeError: 'module' object has no attribute 'append'
Run Code Online (Sandbox Code Playgroud)

这是什么意思?我有一种感觉,因为我正在创建一个模块列表,但不应该这样做吗?

Wil*_*den 5

libs是模块列表,模块libs[i]也是如此. libs[i].append失败,因为您无法向模块添加内容.

严格地说,这个代码实际上是不太可能的情况下,运行libs[i]的是,公开自己的模块append方式(与兼容的签名),但是这肯定是你想要的东西是不行的.


您可以通过转换libs为元组列表来实现您想要的,其中第一个元素是库,第二个元素是与该库关联的函数列表:

for line in lines:
    lineContents = line.split()
    self.libs.append((importlib.import_module(lineContents[0]), lineContents[1:]))
Run Code Online (Sandbox Code Playgroud)

然后,你可以访问图书馆iself.libs[i][0]和功能jself.libs[i][1][j].

如果需要,您还可以__init__使用切片,列表推导with语句来消除循环并将整个行减少到只有三行:

with open(sceneFile, 'r') as scenes:
    lines = (l.split() for l in scenes)
    self.libs = [(importlib.import_module(l[0]), l[1:]) for l in lines]
Run Code Online (Sandbox Code Playgroud)