Python classes and objects with __init__ and self, stepped through line by line.
In one line
A class bundles data and functions into a template, and an object is one item made from it. In Python you call the class like a function to get an object.
Why you need it
With three plants you end up with fern_water, cactus_water, ivy_water and so on, one variable per plant. Each needs its own watering code, and adding water to the wrong variable is easy.
Put the name, the water each plant wants, the water it got and give() into one Plant class, and each plant is a single variable. Ten plants means ten calls to Plant(...).
Everyday picture
Picture a plant label form with three boxes: name, daily water, water given today. The form is the class; every filled-in label stuck in a pot is an object. __init__ is the moment you write the first values on a fresh label.
Press Run to try your edited code right away. The step-through and the output above follow the original code.
When to use it
Several records share the same shape (plants, students, orders, products)
You want data and the functions that change it kept together (watering, reporting status)
You keep building dicts with the same keys. Those keys are attribute candidates.
A class that only stores values can shrink with @dataclass from dataclasses. Python writes __init__, __repr__ and __eq__ for you (Python 3.7+).
Common mistakes
Forgetting self in a method
Plant().give(10) really passes two values, like Plant.give(the_object, 10). Without self to catch the first one, Python complains that one argument too many arrived.
Wrong
classPlant:defgive(ml):print(ml)Plant().give(10)
When you run itTypeError: Plant.give() takes 1 positional argument but 2 were given
a = Plant("Mint", 100)b = ab.give(40)print(a.water)
Show the answer
Answer: 2. 40b = a does not copy the object. Both names point to the same plant, so water given through b shows up through a as well.
Question 2
Inside a method, what is self?
Show the answer
Answer: 1. The object written before the dot in the call In fern.give(120), self is fern. The name is only a convention, so another name would work, but everyone writes self to keep code readable.
Questions people ask
Do I always have to write self?
Yes, as the first parameter of every method. You do not pass it when calling; the object before the dot is filled in for you.
Is __init__ the constructor?
It is the method that fills in the first values right after the object is created. People usually call it the constructor, and it runs when you call the class.
Do attributes need to be declared?
No. They appear the first time you assign self.name = value. Creating all of them inside __init__ still makes the class easier to read.