Line At A Time
Lesson 5: Objects That Remember
Objects That Remember Change an object's values; it remembers!
1class Dog:
2 def __init__(self, name, age):
3 self.name = name
4 self.age = age
5
6 def birthday(self):
7 self.age = self.age + 1
8 print(f"{self.name} is now {self.age}!")
9
10rex = Dog("Rex", 3)
11rex.birthday()
12rex.birthday()
Terminal
$ python3 main.py
Rex is now 4!
Rex is now 5!
Every line, explained
class Dog:
class Dog: defines a class: a blueprint describing what every Dog can do. Like if and def, the line ends with a colon and everything belonging to the class is indented underneath.
def __init__(self, name, age):
The __init__ method (two underscores each side, "dunder init") is special: Python runs it AUTOMATICALLY whenever a new object is built. It is where you fill in the object's starting values. Two values this time.
self.name = name
This dog's name box.
self.age = age
This dog's age box.
def birthday(self):
A method that CHANGES the object.
self.age = self.age + 1
Adds 1 to this dog's stored age. The object keeps the new value; objects remember!
print(f"{self.name} is now {self.age}!")
print(...) works exactly as in Intro to Python.
rex = Dog("Rex", 3)
rex is born aged 3.
rex.birthday()
First birthday: 3 becomes 4.
rex.birthday()
Second birthday: rex REMEMBERED being 4, so now he is 5. Each object carries its own memory around.