gpt4 book ai didi

python - LPTHW Ex47 属性错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:14:34 25 4
gpt4 key购买 nike

我正在处理 LPTHW,但遇到了 Ex47 的属性错误。我浏览过这个网站并在谷歌上搜索帮助,但似乎找不到任何东西。

我得到的错误是这样的:

  Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/nose/case.py", line 197, in runTest
self.test(*self.arg)
File "/Users/Donatron/temp/My Python Stuff/projects/ex47/tests/ex47_tests.py", line 26, in test_map
start.add_paths({'west': west, 'down': down})
File "/Users/Donatron/temp/My Python Stuff/projects/ex47/ex47/game.py", line 12, in add_paths
self.paths.update(paths)
AttributeError: 'list' object has no attribute 'update'

我的“游戏”代码如下所示:-

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)

我的“测试”代码如下所示:-

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

这让我很头疼!我哪里出错了?

提前感谢您的帮助:-)

最佳答案

self.paths应该是dict {}不是列表

self.paths = {}

dictsgetupdate方法,你的self.paths是一个列表[]它没有更新方法,这就是您收到错误的原因。

在错误中您可以看到 start.add_paths({'west': west, 'down': down})它正在添加一个传递给 self.paths 的字典它试图调用 self.paths.update方法但失败为 self.paths设置为list而不是dict {} .

return self.paths.get(direction, None) # 使用dict.get方法

self.paths.update(paths) # 使用dict.update方法。

dict.get(direction, None)返回None默认情况下,如果 key dict 中不存在,您可以指定任何默认返回值来代替 None

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

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