属性错误:';可打开';对象没有属性';尝试打开&x27;python
我已经构建了用于类的代码,并将其包含在下面。此外,我还包含了用于测试的代码,但由于某些原因,我得到了可怕的属性错误:';可打开';对象没有属性';尝试打开&x27;python,python,python-3.x,Python,Python 3.x,我已经构建了用于类的代码,并将其包含在下面。此外,我还包含了用于测试的代码,但由于某些原因,我得到了可怕的属性错误:“Openable”对象没有属性“try\u open”。有人能告诉我为什么会发生这种情况和/或提供解决方案吗 class Thing: """a class for representing physical objects in a game attributes: name (str), location (str)""" def __init__(
属性错误:“Openable”对象没有属性“try\u 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)
您尚未在
Openable
或其父类上定义try\u open
在
test\u open
函数中调用o。尝试\u 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.
所以应该尝试什么?