I am attempting to create a nested dictionary 'world'. Due to the planned size and complexity I am hoping to automate the creation a bit. However, when I attempt to run it, I get "AttributeError: 'Pathway' object has no attribute 'hidden'". The intended structure of the dictionary is as follows
**world
class Pathway(dict):
def __init__(self, hidden, travelType):
self.dict = {
self.hidden : hidden,
self.travelType : travelType
}
class Room(dict):
def __init__(self, hidden, pathways):
self.dict = {
self.hidden : hidden,
self.pathways : pathways
}
class Location(dict):
def __init__(self, rooms, alignment):
self.dict = {
self.alignment : alignment,
self.rooms : rooms
}
p1 = Pathway(True, "teleport")
voidRoom = Room(True, [p1])
villageEntrance = Room(False, [p1])
void = Location([voidRoom], "neutral")
village = Location([villageEntrance], "good")
world = {
"void" : void,
"village" : village
}
def locationDataRetrieval(path):
val = world.get(path)
return val
print(world)
I looked up proper syntax for dictionaries and as far as I can see I have it correct. I also attempted removing the pathway class but the error moved on to the next class.
This is python, not javascript.
class Pathway(dict):
def __init__(self, hidden, travelType):
self.dict = {
self.hidden : hidden,
self.travelType : travelType
}
PEP 8
asks you to instead name it travel_type
.
It's not strictly necessary to define all attributes in
the __init__()
constructor, but it's good practice, it's considered polite.
Here, you're attempting to dereference self.hidden
before
you have assigned anything to it.
A typical ctor would look like:
def __init__(self, hidden, travel_type):
self.hidden = hidden
self.travel_type = travel_type
After that it's perfectly fine to dereference self.hidden
.
You can even put it in a dict
if you like.
It's unclear why that would be desirable, though.
I recommend you settle on object attributes, or settle on dicts,
without trying to mix them.
Storing the same thing in two places tends to lead to maintenance trouble
later on.
A @dataclass decorator can save you the trouble of writing a ctor:
from dataclasses import dataclass
@dataclass
class Pathway:
hidden: bool
travel_type: str