python - 类中的类型错误

标签 python python-3.x

我正在尝试创建一个名为 OpenableThing 子类。在定义 __init__() 方法时,我得到一个

type error: Traceback (most recent call last):
  File "/Users/jaredbanton8/Documents/things.py", line 57, in <module>
    book1 = Openable("Necronomicon", "book shelf")
  File "/Users/jaredbanton8/Documents/things.py", line 40, in __init__
    super().__init__(name)
TypeError: __init__() missing 1 required positional argument: 'location'

在我的代码中,我包含了对我的类的测试。我不确定是什么导致了这个错误。我的代码是:

    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 is_open(t):
                return True
        def __init__(self, name, location, o=0):
            """assigns values to attributes"""
            super().__init__(name)
            super().__init__(location)
            is_open = 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)

最佳答案

你应该用两个参数调用一次__init__,而不是用一个参数调用两次:

super().__init__(name, location)

此外,如果您使用的是 Python 2,super 还需要一些参数:

super(Openable, self).__init__(name, location)

关于python - 类中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29661069/

相关文章:

Python 3 和带有进度条的请求

Python 漂亮的矩阵打印

python - 在 Python 请求中停止文件下载

python - 如何在Python中创建一个在新选项卡中打开的html链接

python - Pygame - 在给定区域随机生成对象

python - 想要用Python中的新字符覆盖文本文件中特定行上的特定字符

Python:有关 Python 函数实现的信息

python - PyGObject 与 GStreamer 示例?

python - 使用 flask-simpleldap 在 Flask 应用程序中进行身份验证

python - 在python中使用numpy创建一个动态数组