【问题标题】:importing a class from another file [duplicate]从另一个文件导入一个类[重复]
【发布时间】:2014-09-14 19:53:20
【问题描述】:

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

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

我已经尝试研究过这个,但到目前为止还没有找到解决方案,希望你能帮助我。

【问题讨论】:

  • parser 是 Python 中的内置模块,您的脚本正在导入该模块。
  • parser 已经是 Python 模块的名称。你应该给你的模块另一个名字。
  • 可能重复(问题/帐户):stackoverflow.com/q/24868635/3001761
  • 这个问题似乎跑题了,因为它没有展示对python的基本了解

标签: python class object import


【解决方案1】:

试试

from .parser import Parser

这仅在您不执行脚本而是将其用作包时才有效。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多