AttributeError:'Openable'对象没有属性'try_open'python

时间:2015-04-15 22:54:13

标签: python python-3.x

我已经构建了与类一起使用的代码,并将其包含在下面。此外,我包含了测试代码,但出于某种原因,我得到了可怕的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)

1 个答案:

答案 0 :(得分:2)

您尚未在try_open或其父类上定义Openable


test_open功能中,您拨打o.try_open()并传递Openable的实例。您需要做的是在OpenableThing的定义中定义新方法。例如:

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.