从另一个文件导入类

2 投票
1 回答
8352 浏览
提问于 2025-04-18 14:27

我有三个不同的文件,我想在一个文件中使用另一个文件里的类。

1) __init__.py(这个文件是空的)

2) assembler.py

3) parser.py(这个文件里有一个叫 Parser 的类)

assembler.py 文件的内容:

from parser import Parser
file_location = r'C:\Users\location'
p = Parser()
print p.getCommands()

parser.py 文件的内容:

class Parser(object):
    def __init__(self, file_location):      
        #get the files contents
        file = open(file_location,'r');
        self.contents = file.read();
        file.close();
        self.contents = self.contents.split('\n')
        self.contents = self.removeComments(self.contents)

    def removeComments(self, liste):
        remove = []

        for command in liste:
            if command == '':
                remove.append(command)
            if r'//' in command:
                remove.append(command)
            if not ('@' in command or ';' in command or '=' in command):
                remove.append(command)

        for element in remove:
            if element in liste:
                liste.remove(element)

        return liste

    def getCommands(self):
        return self.contents

我遇到了一个错误:

Traceback (most recent call last):
File "assembler.py", line 1, in <module>
    from parser import Parser
ImportError: cannot import name Parser

我尝试过查找解决办法,但到目前为止还没有找到,希望你们能帮帮我。

1 个回答

0

试试看

from .parser import Parser

这个方法只有在你不直接运行脚本,而是把它当作一个包来使用时才有效。

撰写回答