Book
Module 7 - Section 1 - Classes
Module 7 - Section 1 - Classes
Completion requirements
View
After the completion of this module the students will be able to:
- identify a class inside Python code
- present the necessary parts for constructing a class
- create code to construct a simple class
- create and use methods in a class
- distinguish the references from the objects of a class
- rewrite the classes code to implement constructors
7.1.5 - References
Take a look at the following code.
class Person():
def __init__(self):
self.name = ""
self.money = 0
bob = Person()
bob.name = "Bob"
bob.money = 100
nancy = Person()
nancy.name = "Nancy"
print(bob.name, "has", bob.money, "euros.")
print(nancy.name, "has", nancy.money, "dollars.")
To visualize click on the link to transfer to http://www.pythontutor.com
The code above has nothing new. But the code below has a diffrence:
class Person():
def __init__(self):
self.name = ""
self.money = 0
bob = Person()
bob.name = "Bob"
bob.money = 100
nancy = bob
nancy.name = "Nancy"
print(bob.name, "has", bob.money, "euros.")
print(nancy.name, "has", nancy.money, "euros.")
To visualize click on the link to transfer to http://www.pythontutor.com
The difference in pythontutor is in line 10. nancy is a reference to bob. Besides reference, we can call this address, pointer, or handle. A reference is an address in computer memory for where the object is stored. This address is a hexadecimal number which, if printed out, might look something like 0x1e504. When the code is executed, the address is copied rather than the entire object the address points to.