Methods That Use self
Let a method use the object's own values.
1class Dog:
2 def __init__(self, name):
3 self.name = name
4
5 def bark(self):
6 print(f"{self.name} says woof!")
7
8rex = Dog("Rex")
9rex.bark()
$ python3 main.py
Rex says 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 __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- Stores this dog's name.
def bark(self):- A second method. Because it gets self, it can look at THIS dog's stored values.
print(f"{self.name} says woof!")- An f-string using self.name, so every dog barks its own name. When rex barks, self is rex.
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.
rex.bark()- rex barks, and the method prints rex's own name.