I am working on my first python project, a tower defense game called Ants vs Bees. I need some assistance understanding one aspect of the starter code, namely the implementation of tracking the entrances of a specific place.
import random
from ucb import main, interact, trace
from collections import OrderedDict
class Place(object):
"""A Place holds insects and has an exit to another Place."""
def __init__(self, name, exit=None):
"""Create a Place with the given NAME and EXIT.
name -- A string; the name of this Place.
exit -- The Place reached by exiting this Place (may be None).
"""
self.name = name
self.exit = exit
self.bees = [] # A list of Bees
self.ant = None # An Ant
self.entrance = None # A Place
# Phase 1: Add an entrance to the exit
if self.exit is not None:
exit.entrance = self
I do not understand Phase 1, i.e. the last two lines of this starter code. How can we use dot notation to put one instance variable in front of another instance variable? What does equating it to self do? I have tried isolating this class, making objects and then printing both attributes individually but it throws me errors, leading me to suspect that perhaps the starter code is faulty? It would mean a huge deal to me to you might assist me in understanding how they are adding an entrance to the exit using exit.entrance = self?
exit.entrance = self, it's not referring toentranceas a local variable at all, it's just describing what property ofexitto set. The fact that you also have a local variable namedentranceis just coincidence.exit.entrancemeans set the value ofentranceinexitobject toself. Its not checking equality, rather assigning the value toentranceDot Notationsetattr(exit, 'entrance', self), notsetattr(exit, entrance, self).selfhas nt special meaning. It's just the name of the local variable that happens to hold a reference thePlaceinstance being initialized. In your code,selfandexitare two independentPlaceinstances. Writingself.entrancereferences theentranceattribute ofself; writingexit.entrancereferences theentranceattribute ofexit.Placeinstance, you have the option of specifying an additionalPlaceinstance via theexitparameter to serve as the "exit" of the new place. If anexitPlaceis provided, then the newPlace(aka,self) is assigned to theentranceattribute of theexit.