【问题标题】:Python module working on 2.7 but not on 3.5 [duplicate]Python模块适用于2.7但不适用于3.5 [重复]
【发布时间】:2016-10-08 18:36:54
【问题描述】:

这是我的代码:

Animals/__init__.py

from Mammals import Mammals

from Bird import Bird

动物/哺乳动物.py

class Mammals(object):

    def __init__(self):
        self.members = ['Tiger', 'Elephant','Wild Cat']

    def print_members(self):
        for member in self.members :
            print('this is a member :' + member)

Animals/Bird.py

class Bird(object):

    def __init__(self):
        self.birds = ['sparrow','robbin','duck']

    def print_members(self):
        print('printing birds in bird class')
        for bird in self.birds:
            print('this is a bird '+ bird)

test.py

from Animals import Mammals, Bird

mam = Mammals()
bird = Bird()

mam.print_members()

bird.print_members()     

我已经安装了 Python 3 (MacOSX),并且正在将它与 virtualenv 一起使用。此代码适用于 2.7,但不适用于 python3.5。它总是给ImportError: No module named Mammals

【问题讨论】:

  • 它是 Animals/__init__.py
  • from .Mammals import Mammals 这里少了一个点。命令 2to3 将为您完成。
  • @非常感谢。问题已解决。

标签: python macos python-2.7 python-3.x


【解决方案1】:

Python 3 区分了相对导入和绝对导入,放弃了对隐式相对导入的支持。

您的代码在 python2 中运行,因为解析器暗示了 BirdsMammals 的相对导入,但 python3 停止这样做。

运行2to3 为您的文件将修复它。

from .Mammals import Mammals
from .Bird import Bird

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2016-09-19
    • 2021-09-25
    • 2018-01-07
    • 1970-01-01
    • 2021-02-07
    相关资源
    最近更新 更多