我正在尝试创建一个名为 Openable
的 Thing
子类。在定义 __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/