我已经构建了与类一起使用的代码,并将其包含在下面。此外,我包含了测试代码,但出于某种原因,我得到了可怕的AttributeError: 'Openable' object has no attribute 'try_open'
。谁能告诉我为什么会发生这种情况和/或提供修复?
class Thing:
"""a class for representing physical objects in a game
attributes: name (str), location (str)"""
def __init__(self, name, location):
"""assigns values to attributes"""
self.name = name
self.location = location
def description(self):
"""returns str that describes the state of the object
str -> str"""
return str('Nothing special.')
def test(t):
"""Tests the name, location, and description method of t
Thing -> None"""
print(t.name + " (" + t.location + "): " + t.description())
key1 = Thing("golden key", "under door mat")
test(key1)
key2 = Thing("rusty key", "jacket pocket")
test(key2)
class Openable(Thing):
"""a class for representing those physical objects which can be opened
inherited attributes: all"""
def is_open(t):
"""returns a bool whether the object is open or not
str -> bool"""
if o.is_open():
print("the " + o.name + " should now be open.")
else:
print("the " + o.name + " should now be open.")
def __init__(self, name, location, o=False):
"""assigns values to attributes"""
super().__init__(name, location)
self.isOpen = o
def test_open(o):
"""Tests an attempt to open o
Openable -> None"""
print()
test(o)
print("Attempting to open the " + o.name + "...")
if o.try_open():
print("The " + o.name + " should now be open.")
else:
print("The " + o.name + " should now be closed.")
test(o)
book1 = Openable("Necronomicon", "book shelf")
test_open(book1)
window1 = Openable("side window", "north wall", True)
test_open(window1)
答案 0 :(得分:2)
您尚未在try_open
或其父类上定义Openable
。
在test_open
功能中,您拨打o.try_open()
并传递Openable
的实例。您需要做的是在Openable
或Thing
的定义中定义新方法。例如:
class Openable(Thing):
def __init__(self):
# Your other code here
def is_open(self):
# Your other code here
def try_open(self):
# Some logic here for whatever you expect try_open to do.