A class in Python is a blueprint for objects: you define it with the class keyword, give it an __init__ method to set up each new object, and add methods that work on that object's data. Calling the class, like Account("Sam"), creates an instance.
A minimal class in Python
This class stores an owner and a balance, and has one method that changes the balance:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
return self.balance
acct = Account("Sam", 100)
print(acct.deposit(50))
print(acct.owner, acct.balance)
Example output:
150
Sam 150
The Python tutorial describes the mechanics: when a class definition is left normally, a class object is created, and class instantiation uses function notation. In its words, you can "pretend that the class object is a parameterless function that returns a new instance of the class". Here the function takes arguments because __init__ asks for them.
What __init__ does
__init__ is the initializer. According to the tutorial, when a class defines it, instantiation automatically invokes it for the newly created instance. Anything you pass in the call, such as "Sam" and 100, arrives as the arguments after self. The tutorial's own example:
>>> class Complex:
... def __init__(self, realpart, imagpart):
... self.r = realpart
... self.i = imagpart
...
>>> x = Complex(3.0, -4.5)
>>> x.r, x.i
(3.0, -4.5)
__init__ is optional. A class that doesn't define one is created with no arguments. It should also not return a value; its job is to fill in attributes on the instance that already exists.
What self means
When you call acct.deposit(50), Python passes acct as the first argument of deposit. The tutorial puts it this way: the call x.f() "is exactly equivalent to MyClass.f(x)". So self is the instance the method was called on, and self.balance reads or writes that instance's attribute.
The name is a convention. The tutorial states that self "has absolutely no special meaning to Python". Keep the convention anyway, because every tool and reader expects it. A common beginner error is forgetting the parameter. If you write def deposit(amount):, then acct.deposit(50) passes two arguments (the instance and 50) to a function that accepts one, and Python raises a TypeError about the number of positional arguments.
Instance variables vs class variables
Variables assigned through self belong to one instance. Variables assigned directly in the class body are shared by all instances. The tutorial's summary: instance variables are for data unique to each instance, and class variables are for attributes and methods shared by all instances.
class Dog:
kind = "canine" # class variable, shared
def __init__(self, name):
self.name = name # instance variable, unique
d = Dog("Fido")
e = Dog("Buddy")
print(d.kind, e.kind)
print(d.name, e.name)
Example output:
canine canine
Fido Buddy
The shared mutable list trap
Sharing is fine for a string like "canine" but causes a classic bug with a list or dict. The tutorial shows a class with tricks = [] in the class body and an add_trick method that appends to self.tricks. Adding one trick to one dog changes every dog:
>>> d.add_trick('roll over')
>>> e.add_trick('play dead')
>>> d.tricks # unexpectedly shared by all dogs
['roll over', 'play dead']
The fix is to create the list inside __init__, so each instance gets its own:
class Dog:
def __init__(self, name):
self.name = name
self.tricks = [] # a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
Now d.tricks is ['roll over'] and e.tricks is ['play dead']. As a rule, put mutable starting values in __init__, not in the class body.
Inheritance: one class building on another
Put the base class in parentheses to create a derived class. The derived class gets the base class's methods and can override any of them:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.02):
Account.__init__(self, owner, balance)
self.rate = rate
def add_interest(self):
self.balance += self.balance * self.rate
s = SavingsAccount("Sam", 1000)
s.add_interest()
print(s.balance)
Example output:
1020.0
The tutorial notes that an overriding method may want to extend the base method rather than replace it, and that the way to do so is to call BaseClassName.methodname(self, arguments), which is what Account.__init__(self, owner, balance) does above. Python also has a built-in super() for the same job, and it is the usual choice when classes have several parents.
Two built-in functions check relationships. isinstance(obj, int) is true only if obj.__class__ is int or a class derived from it. issubclass(bool, int) is True because bool is a subclass of int, while issubclass(float, int) is False. Python also allows several base classes, class C(Base1, Base2), and for simple cases the tutorial describes the attribute lookup as depth-first, left to right.
Private-looking names
Python has no enforced private attributes. By convention, a single leading underscore, as in _cache, marks a name as internal. A name with two leading underscores and at most one trailing underscore, such as __update, is rewritten by the interpreter to _classname__update. The tutorial explains this is meant to avoid clashes with names in subclasses, not to hide data from other code.
Dataclasses: less boilerplate for data-holding classes
If a class mostly stores values, the dataclasses module writes __init__ for you. This is the first example from the Python docs:
from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str
unit_price: float
quantity_on_hand: int = 0
def total_cost(self) -> float:
return self.unit_price * self.quantity_on_hand
The decorator adds an __init__ that takes the fields in the order they are defined, with defaulted fields optional. It also adds a __repr__ that shows the class name and each field, such as InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10), and an __eq__ that requires both instances to be of the identical type.
Dataclasses guard against the shared-list trap too. A field written as x: list = [] raises a ValueError, because defaults are stored as class attributes and would be shared. The docs' fix is a default factory:
from dataclasses import dataclass, field
@dataclass
class D:
x: list = field(default_factory=list)
With that, D().x is not D().x: each instance gets its own list.
Common mistakes with classes in Python
- Forgetting
self. Without it as the first parameter, calling the method raises aTypeErrorabout too many positional arguments. Inside the method, a barebalancerefers to a local variable, not the attribute, so useself.balance. - Mutable class variables. Lists, dicts and sets in the class body are shared by every instance. Create them in
__init__. - Calling the class without parentheses.
acct = Accountbinds the class itself, not an instance. WriteAccount("Sam"). - Forgetting to call the base initializer. A derived class that defines its own
__init__replaces the base one. If you don't call the base__init__, the attributes it sets, likeownerabove, won't exist.
For the surrounding basics, see Python for beginners: core concepts, and for what happens when a method raises, Python exception handling with try and except.
Frequently asked questions
- What is the difference between a class and an object in Python?
- A class is the blueprint, created by a class statement. An object (also called an instance) is one thing built from that blueprint by calling the class, for example Account('Sam'). One class can produce any number of instances, and each instance keeps its own data.
- Is self a keyword in Python?
- No. The Python tutorial calls self a convention and says the name has no special meaning to Python. The instance is passed as the first argument of a method, and by convention that parameter is named self. Using another name works but confuses every reader.
- Do I need __init__ in every class?
- No. A class without __init__ can still be instantiated with no arguments. Write __init__ when each instance needs starting data, such as a name or a balance.
- When should I use a dataclass instead of a regular class?
- Use @dataclass from the dataclasses module when the class mainly holds data. It generates __init__, __repr__ and __eq__ from the annotated fields, so you write far less boilerplate. Use a regular class when you need custom construction logic.