What Is a Class?
Write a blueprint and build an object from it.
1class Dog:
2 def bark(self):
3 print("Woof!")
4
5rex = Dog()
6rex.bark()
$ python3 main.py
Woof!
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 bark(self):- A def inside a class is a method: something every Dog can do. Its first parameter is always self: the dog being asked to bark. You never pass self yourself; Python does it for you.
print("Woof!")- print(...) works exactly as in Intro to Python. Indented twice: inside the method, inside the class.
rex = Dog()- 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. rex now holds one actual dog.
rex.bark()- The dot asks the object to do one of its tricks: rex.bark() means "rex, bark!".