7.1 Objects and ReferencesBefore turning our attention to the topic of linked structures, it will be helpful to quickly review variable references and objects. Linked structures are built around the concept of objects and references to objects that are stored in variables. ReferencesIn Python, a variable is a named location that stores a reference to an object. They do not store the data themselves. For example, the following statements name = "John Smith" idNum = 42 avg = 3.45 create objects and variables that can be illustrated as shown below If we assign a new reference to an existing variable, idNum = 70 it replaces the original reference When all references to an object are removed, the object is marked as garbage and will eventually be destroyed. That is, the memory used by that object is returned to the program for reuse. The None ReferenceA variable can have a special value avg = None This value is used to initialize a variable that should exist, but not store a reference to any particular object. AliasesConsider the following code segment, pointA = Point(2, 8) pointB = Point(15, 7) pointC = Point(2, 8) which creates three point objects using the When two variables reference the same object, target = pointC they are aliases. Thus, the object is known by multiple names. Sometimes it is important to know if a variable is an alias for a given object. When we use the if target == pointA : print("These are the same points.") else : print("They are not the same points.") will print They are the same points. since the two points contain the same x- and y-coordinates and thus are the same point in the Cartesian coordinate system. Question 7.1.1
What would be the result if we changed the condition part in the above code segment to if target == pointB : The code would print Thus, we can not use the if target is pointA : print("The variables are aliases") else : print("They are not aliases") The They are not aliases. since each variable refers to a different object. While those objects represent the same point in space, they are not the same object. Question 7.1.2
What would be the result if we changed the condition part in the above code segment to if target is pointC : # read this as "if target is an alias for pointC" The code would print Python also provides the Question 7.1.3
What is the result of executing this code segment? if target is not pointC : # read this as "if target is not an alias for pointC" print("They are not aliases") else : print("They are aliases") It will print
|