To make a class in Python, use the class keyword, a name in CapWords style, and a body that defines an __init__ method for setting up instance attributes plus any other methods. Calling the class, for example Person("Ada", 36), creates an instance. For classes that mostly hold data, the dataclass decorator generates the boilerplate for you.
This guide covers the syntax, instance and class attributes, the three kinds of methods, inheritance, and the modern shortcuts for Python 3.12 and later.
super()self is the instance the method was called on. Python passes it automatically, so you write ada.greet() but define greet(self). __init__ is the initializer, not the constructor: the object already exists when it runs, and it must return None.
Instance attributes belong to one object and are set through self. Class attributes are defined in the class body and shared by every instance.
Avoid mutable class attributes such as items = []. Every instance would share the same list. Create mutable state inside __init__ instead.
| Kind | Decorator | First parameter | Typical use |
|---|---|---|---|
| Instance method | none | self | Work with one object's data |
| Class method | @classmethod | cls | Alternative constructors |
| Static method | @staticmethod | none | Helper related to the class |
Python has no private keyword. By convention a leading underscore means "internal". Use @property to add validation without changing how callers use the attribute.
Because balance has no setter, acct.balance = 10 raises AttributeError, so changes must go through deposit.
super()A subclass lists its parent in parentheses and calls super() to reuse the parent's behaviour.
Prefer composition (holding another object) when the relationship is "has a" rather than "is a".
For data-holding classes, @dataclass generates __init__, __repr__ and __eq__ from type-annotated fields.
Use field(default_factory=...) for mutable defaults. For hand-written classes, define __repr__ so objects print usefully in logs and the debugger, and __str__ for a user-facing form.
self in Python?It is the conventional name of the first parameter of an instance method and refers to the object the method is called on. It is not a keyword, but you should always use that name.
__new__ creates the object and __init__ initializes it. You rarely override __new__, mainly for immutable types or singletons.
object?No. In Python 3 every class inherits from object implicitly, so class Person: is enough.
Use a dataclass when the class mainly stores values and you want generated __init__, __repr__ and comparison methods. Use a normal class when you need custom construction logic.
Define a class with class Name:, set per-object state in __init__ through self, and add instance, class and static methods as needed. Use properties for controlled access, super() for inheritance, and @dataclass to remove boilerplate for data holders.