Note: This is not a duplicate of AttributeError: type object has no attribute. I am trying to code a text-adventure.
class place(object):
def __init__(self):
super(place, self).__init__()
self.directions = {
"N":None,
"S":None,
"E":None,
"W":None,
"NE":None,
"NW":None,
"SE":None,
"SW":None
}
def add_directions(self, *args): #There's a problem with putting *args because it takes self as string
#I'm sure there is a more elegant way to do this
for direction in args:
for key in self.directions:
self.directions[key] = direction
print(self)
place()
place.add_directions(place, "The Dark Room")
I wish to add "The Dark Room" to the class variable "self.directions". However, whenever I do so, they give this error:
"C:\Program Files (x86)\Python38-32\python.exe" "C:/Users/samue/Documents/School/Y3 2020/Computer Science/Python/TextAdventure/The Dark Asylum.py"
Traceback (most recent call last):
File "C:/Users/samue/Documents/School/Y3 2020/Computer Science/Python/TextAdventure/The Dark Asylum.py", line 25, in <module>
place.add_directions(place, "No")
File "C:/Users/samue/Documents/School/Y3 2020/Computer Science/Python/TextAdventure/The Dark Asylum.py", line 20, in add_directions
for key in self.directions:
AttributeError: type object 'place' has no attribute 'directions'
I know my understanding of objects are not that good, but could someone help me to assign individual directions, in string to each key in the class variable self.directions
? Is it something wrong with *args
in the function add_directions
?
place.add_directions(place, "The Dark Room")
In this line, you are referencing the class place and not an instance of the place class,
In python and other Object oriented programming languages, you first need to instantiate or initialize a class before accessing its members.
place_instance = place()
place_instance.add_directions("The Dark Room")
It is not necessary to pass the class as self
as you have done, self
is need to define methods, not when calling methods.
To make this code more readable, consider using an uppercase letter for place. It could be written as class Place()