Tools
Log in
English

Learn to codePython

Python classes and objects

Based on Python 3.12f-string · Python 3.6+

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.

Example code

main.py · 23 lines
class Plant:    def __init__(self, name, thirst):        self.name = name        self.thirst = thirst        self.water = 0     def give(self, ml):        self.water += ml        return self.water >= self.thirst     def status(self):        if self.water >= self.thirst:            return f"{self.name}: enough ({self.water}ml)"        return f"{self.name}: needs {self.thirst - self.water}ml more"  fern = Plant("Fern", 300)cactus = Plant("Cactus", 50)fern.give(120)done = cactus.give(80)print(fern.status())print(cactus.status())print(done, fern.water, cactus.water)

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

class Plant:    def give(ml):        print(ml)  Plant().give(10)

When you run itTypeError: Plant.give() takes 1 positional argument but 2 were given

Fixed

class Plant:    def give(self, ml):        print(ml)  Plant().give(10)

When you run it10

Assigning without self.

water = 0 creates a local variable that lives only inside __init__. It vanishes when the function ends, so the object never gets a water attribute.

Wrong

class Plant:    def __init__(self, name):        self.name = name        water = 0  p = Plant("Fern")print(p.water)

When you run itAttributeError: 'Plant' object has no attribute 'water'

Fixed

class Plant:    def __init__(self, name):        self.name = name        self.water = 0  p = Plant("Fern")print(p.water)

When you run it0

Typing __int__ instead of __init__

With one letter wrong, Python does not treat the method as the initializer. The class then accepts no arguments, and passing a name fails.

Wrong

class Plant:    def __int__(self, name):        self.name = name  p = Plant("Fern")

When you run itTypeError: Plant() takes no arguments

Fixed

class Plant:    def __init__(self, name):        self.name = name  p = Plant("Fern")print(p.name)

When you run itFern

Check yourself

Question 1

After b = a, water goes to b. What is a.water?

a = Plant("Mint", 100)b = ab.give(40)print(a.water)

Show the answer

Answer: 2. 40 b = 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.