艰苦学习Python 47鼻子测试NameError

时间:2018-08-24 11:25:48

标签: python python-3.x

我正在尝试从“学习Python 3”这本书中学习Python 3,但是尝试在练习47中使用鼻子测试运行测试时遇到错误,在顶层ex47目录中运行命令。

我的文件夹结构是:

ex47
  -bin
  -docs
  -ex47
      __init__.py
      game.py
  -test
      __init__.py
      ex47_tests.py
  setup.py

init 文件的内容为空白。对于其他文件,它是: game.py

class Room(object):

    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.paths = {}

    def go(self, direction):
        return self.paths.get(direction, None)

    def add_paths(self, paths):
        self.paths.update(paths)

setup.py

try:
    from setuptools import setup
except ImportError:
    from distutials.core import setup

config = {
    'decription' : 'My Project',
    'author' : 'My Name',
    'url' : 'URL to get it at.',
    'download_url' : 'Where to download it.',
    'author_email' : 'My Email',
    'version' : '0.1',
    'install_requires' : ['nose'],
    'packages' : ['ex47'],
    'scripts' : [],
    'name' : 'ex47'
}

setup(**config)

ex47_tests.py

from nose.tools import *
import ex47

def test_room():
    gold = Room("GoldRoom",
                """This room has gold in it you can grab. There's a
                door to the north.""")
    assert_equal(gold.name, "GoldRoom")
    assert_equal(gold.paths, {})

def test_room_paths():
    center = Room("Center", "Test room in the center.")
    north = Room("North", "Test room in the north.")
    south = Room("South", "Test room in the south.")

    center.add_paths({'north' : north, 'south' : south})
    assert_equal(center.go('north'), north)
    assert_equal(center.go('south'), south)

def test_map():
    start = Room("Start", "You van go west and down a hole.")
    west = Room("Trees", "There are trees here, you can go east.")
    down = Room("Dungeon", "It's dark down here, you can go up.")

    start.add_paths({'west' : west, 'down' : down})
    west.add_paths({'east' : start})
    down.add_paths({'up' : start})

    assert_equal(start.go('west'), west)
    assert_equal(start.go('west').go('east'), start)
    assert_equal(start.go('down').go('up'), start)

尝试在PowerShell中运行此命令会给我这些与未找到Room类有关的错误。 enter image description here

1 个答案:

答案 0 :(得分:2)

我认为您应该在此处访问顶级模块。例如,将此行添加到您的__init__.py中:

__all__ = ["game"]

然后,像导入其他

一样导入
from game import Room

您还可以使用顶级目录:

from ex34.game import Room

或者以一种简单的方式,将所有文件放在一个目录中以方便地访问它们

ex47
  game.py
  ex47_tests.py
  setup.py