Reputation: 271
I am trying to create a subclass of Thing
called Openable
. When defining the __init__()
method, I get a
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'
In my code, I have included tests for my classes. I am not sure what is causing this error. My code is:
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)
Upvotes: 1
Views: 124
Reputation: 5070
__init__
of class Thing
needs two arguments. In __init__
of class Openable
replace
super().__init__(name)
super().__init__(location)
with
super().__init__(name, location)
Code above will work in Python 3.x. In Python 2.x you need
super(Openable, self).__init__(name, location)
or
Thing.__init__(self, name, location)
Function is_open()
in class Openable
probably should look like
def is_open():
return self.isOpen
def __init__(self, name, location, o=False):
super().__init__(name, location)
self.isOpen = o
and used
if o.is_open():
print("The " + o.name + " should now be open.")
else:
print("The " + o.name + " should now be closed.")
Upvotes: 7
Reputation: 2334
You should call __init__
once with two arguments, not twice with one argument:
super().__init__(name, location)
Additionally, if you were using Python 2, super
would also require some arguments:
super(Openable, self).__init__(name, location)
Upvotes: 8