Skip to content

Python Classes and Objects: __init__, self, Methods, Dataclasses and Inheritance

NeedMyTools Academy

Sign in free to read the full lesson

Sign in or create a free account

Free forever. No card, no paywall.

So far, a product has been a dictionary and the rules about it, such as adding VAT or refusing to sell more than the stock, lived in separate functions. A class puts the data and the rules together in one place. You describe the shape once, then create as many objects from it as you need, each with its own values. Every value you have used is already an object: strings have .upper(), lists have .append(). This lesson builds a Product class that protects its own stock, a Money type that prints itself as dirhams and can be added with +, a dataclass that writes boilerplate for you, and a savings account that inherits from a basic account. Every example runs in your browser.

Quick answer

Define a class with class Name: and set up each new object in __init__(self, ...), storing values as self.name = name. Methods are functions inside the class whose first parameter is self, the object itself. Create an object by calling the class, as in Product("Oud oil", 120), and use obj.method(). __str__ controls how print() shows it. @dataclass generates __init__, __repr__ and == for data holders. class Child(Parent): inherits, and super() calls the parent version.

40 min read and practice · Content checked on 3 December 2026

In this lesson you will

  • Write classes with __init__, attributes and methods
  • Control printing and operators with __str__, __repr__ and __add__, and use dataclasses
  • Extend a class with inheritance and super()

class, __init__, self and methods

A class is a blueprint and each object made from it is an instance. Calling Product("Oud oil", 120, stock=4) creates a new empty object and runs __init__ on it, with the new object passed in as self and the other values as the remaining arguments. self.name = name stores a value on that particular object, so oud and dates each keep their own name, price and stock, and dates.stock printed 0 because it used the default. Class names use CapitalisedWords by convention, while method and attribute names stay lowercase with underscores.

A method is a function defined inside the class. When you write oud.with_vat(), Python passes oud as self for you, which is why the definition has one more parameter than the call. Methods are the place for rules: sell() refuses to go below zero stock by raising ValueError, so no other part of the program can make the stock negative by mistake. Selling 3 returned 360 and left 1, and the second sale of 5 was refused with the message built from the object's own data.

Try it: A Product class that protects its stock
Code
ResultUpdates as you type
Console
  1. Console messages, errors, form data and clicked links appear here.

This printed Oud oil 126.0 0, then 360 1, then Only 1 Oud oil left. Add print(oud) at the end to see the default text, which shows the class name and a memory address; the next section fixes that.

Sign in free to read the full lesson

You are reading the free preview. Create a free account (it takes one minute, no password) to unlock the rest of this lesson and track your progress.

Unlocks after sign-in:

  • 2 more sections with live code examples
  • Common mistakes to avoid
  • Hands-on coding exercise with automatic checks
  • Practice quiz and the graded lesson test
Sign in or create a free account

Free forever. No card, no paywall.

Questions people ask

When should I use a class instead of a dictionary?

Use a dictionary for loose data that you mostly pass along, such as a JSON response. Use a class when the data has rules, such as stock that must not go negative, or when the same shape is used in many places and you want editors to autocomplete its fields.

Does Python have private attributes?

Not enforced ones. A leading underscore, as in self._cost, tells other developers that the attribute is internal. Two leading underscores change the name to avoid clashes in subclasses, but it can still be reached.

What is the difference between a function and a method?

A method is a function that belongs to a class and receives the object as its first argument. len(items) is a function, while items.append(x) is a method of the list object.

What are @property and @staticmethod for?

@property lets a method be read like an attribute, so p.with_vat could work without brackets while still being calculated. @staticmethod marks a helper that lives in the class but does not need self.

Do I need classes to use pandas or FastAPI?

You will use objects from them all the time, such as a DataFrame and its methods. FastAPI also describes request data with classes very similar to dataclasses, so the ideas in this lesson come back directly.

Sources

Facts in this lesson were checked against these official pages on 3 December 2026.

Code examples stay in English and run in a sandbox on your device. If you spot a mistake, tell us through the contact page.