The __init__ Method
Give each object its own starting values.
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5rex = Dog("Rex")
6print(rex.name)
$ python3 main.py
Rex
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):- 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. Besides self, it takes a name, a value the builder must hand in.
self.name = name- This stores the name ON the object itself: self.name is "this dog's name box". Plain name is just the value that was passed in; self.name is where it gets kept.
rex = Dog("Rex")- Writing the class name with brackets, Dog(...), builds a real object from the blueprint. The blueprint is the plan; the object is an actual dog. The "Rex" goes straight to __init__, so the object is born with its name already set.
print(rex.name)- print(...) works exactly as in Intro to Python. The dot reads a value back out: rex.name is whatever was stored on rex.