Programming and IT
Python: classes
A class describes what data an object is made of and what it can do. The `__init__` constructor fills in a new object, and `self` is a reference to the object itself. Below: a minimal working class, the difference between class and instance attributes, and ways to make the code shorter.
In this article
A minimal class#
=
=
return f
=
# War and Peace, 1300 pages
# 1300
Class names start with a capital letter and run words together (UserProfile) —
that is the PEP 8 convention. Calling Book(...) creates an object and passes
the arguments to __init__.
What self is and why it comes first#
self is not a keyword but an ordinary first parameter into which Python passes
the object itself. Writing b.summary() is equivalent to Book.summary(b). That
is why every instance method is declared with self, and data is accessed
through it: self.pages, not just pages.
Two mistakes grow from this. The first is forgetting self in the declaration:
return
# TypeError: Bad.show() takes 0 positional arguments but 1 was given
The second is writing return in __init__. The constructor returns nothing;
any attempt to return a value other than None raises TypeError.
Class attributes and instance attributes#
An attribute declared directly in the class body belongs to the class and is
shared by all objects. An attribute assigned through self belongs to one object.
= 0 # shared by all
= 0 # each object has its own
+= 1
+= 1
, = ,
; ;
# 2 1 3
The trap is a mutable class attribute. A list declared in the class body is one list for everyone:
= # do not do this
, = ,
# ['bread']
The right way is to create the list in __init__: self.items = [].
How an object looks when printed#
By default print(obj) gives something like
<__main__.Book object at 0x10a3f...>. __repr__ sets a readable form:
, = ,
return f
return ==
# Point(1, 2)
# [Point(0, 0)]
# True
__repr__ is used both when printing the object itself and inside lists, so of
the two methods (__str__ and __repr__) start with this one. Without __eq__,
two objects with identical data are considered different.
property, classmethod and dataclass#
A computed property is written as a method with the @property decorator and
used like an ordinary attribute — without parentheses:
, = ,
return *
=
# 12
@classmethod gives you an alternative way to create an object: the first
parameter is the class itself, usually called cls. @staticmethod is just a
function that lives next to the class. How decorators work in general is
explained in the article on Python decorators.
When a class only needs to hold fields, dataclass is shorter: it writes
__init__, __repr__ and __eq__ for you.
:
: = 0
=
# User(name='Anna', age=30)
# True
Practice: write a BankAccount class with a balance field, deposit and withdraw
methods and an is_empty property; when someone tries to withdraw more than
there is, raise ValueError — how to do that is covered in the article on
Python exceptions. Inheritance and the other
principles are in the article on OOP in Python.
Step-by-step plan
- A class with two fieldsDeclare a class, fill the fields in __init__, create two objects and print their fields.
- A method that computesAdd a method that uses self and call it on both objects.
- Compare attributesAdd a class attribute and an instance attribute, change both and look at the difference.
- Readable printingWrite __repr__ and check that the object looks right inside a list.
- Shrink it to a dataclassRewrite a data-holding class with @dataclass and compare the amount of code.
Start learning this in your own space
The plan goes into your repository: tick off stages, keep notes — the change history shows how far you have come.
Check yourself
1.Class A has the constructor "def __init__(self, x): self.x = x". What does print(A(5).x) print?
2.Class Cart has the class attribute items = []. After x = Cart(); y = Cart(); x.items.append(1), what is len(y.items)?
3.Which method should you define so that print(obj) shows a readable description of the object?
4.How do you access a property named area that was declared with @property?
Sources
-
Classes in the Python tutorialThe official explanation of class, self and scopesfree
-
The dataclasses moduleAutomatic __init__, __repr__ and __eq__free
-
PEP 8 — Style GuideNaming rules for classes and methodsfree
Was this helpful?