gpt4 book ai didi

python - 导入模块属性错误,LPTHW ex47

转载 作者:行者123 更新时间:2023-11-30 23:42:06 25 4
gpt4 key购买 nike

我在做example 47摘自“艰难地学习 Python”。

这是我的代码:

from nose.tools import*
from ex47.game import Room

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 can 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)
asset_equal(start.go('west').go('east'), start)
assert_equal(start.go('down').go('up'), start)

但是,当使用nosetest测试此代码时,我收到错误:

Traceback <most recent call last>:
File "c:\Python31\lib\site-packages\nose\case.py", line 197,in runtest
self.test<*self.arg>
File "C:\path\Ex47\skeleton\tests\ex47_tests.py", line 28, in test_map
start.add_paths<{'west': west, 'down':down>}
AttributeError: 'Room' object has no attribute 'add_paths'
<小时/>
Ran 3 tests in 0.030s

FAILED <errors=2>

这似乎很荒谬,因为 add_pathstest_room_paths() 中工作得很好。

我使用的是 Python 3.1、Windows 7。

以下是 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)

最佳答案

您声明“add_paths 在 test_room_paths() 中工作正常”,但您假设测试按照您编写的顺序运行。它们通常按字母顺序运行,这意味着 test_room_paths 尚未执行。

您的 Room 代码看起来不正确,您在 def __init__ 下缩进了 def add_paths,这意味着 add_paths 是在 中本地定义的函数__init__,而不是类中的另一个方法。确保类中的所有 def 关键字均已对齐。

关于python - 导入模块属性错误,LPTHW ex47,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11622350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com