Reputation: 1811
I was going through the code given here : Confused about classes in Learn Python the Hard Way ex43?
when I found out that a dict is defined in the class Map(object) but not in any method. Here is what I mean :
class Map(object):
scenes = {
'central_corridor': CentralCorridor(),
'laser_weapon_armory': LaserWeaponArmory(),
'the_bridge': TheBridge(),
'escape_pod': EscapePod(),
'death': Death()
}
def __init__(self, start_scene):
self.start_scene = start_scene
def next_scene(self, scene_name):
return Map.scenes.get(scene_name)
def opening_scene(self):
return self.next_scene(self.start_scene)
Later the dict is used in next_scene method. I did not know that anything can be defined in a class outside a method except docstring. Can you please explain how this dict is being used?
Upvotes: 1
Views: 475
Reputation: 500873
In a nutshell, there exists a single instance of this dictionary. It is called Map.scenes
and is shared by all instances of the class.
did not know that anything can be defined in a class outside a method except docstring.
In actual fact, you can put pretty much any executable statement inside class
:
class HHGTTG(object):
print 42
Even def
is an executable statement in Python.
Upvotes: 4