Two Dogs
Build two objects from one blueprint.
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5rex = Dog("Rex")
6bella = Dog("Bella")
7print(rex.name)
8print(bella.name)
$ python3 main.py
Rex
Bella
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.
self.name = name- Each new dog gets its OWN name box.
rex = Dog("Rex")- One blueprint...
bella = Dog("Bella")- ...as many objects as you like. Think of one house plan and a whole street of houses. bella's name box is completely separate from rex's.
print(rex.name)- print(...) works exactly as in Intro to Python.
print(bella.name)- print(...) works exactly as in Intro to Python. Two objects, two different names.