Learnings

Python basics, part 5 of 6

Python Classes

A class lets you make your own kind of value, with its own data and its own functions. This page is a rewrite of the Pythofrank classes lesson from February 2017. The original examples are kept in spirit and updated from Python 2.7 to Python 3. Most of the page uses one small bank: a person, an account and a savings account.

A class and an object

A class is a plan. It says what data a thing holds and what it can do. An object is one thing built from that plan. An object is also called an instance of its class.

You already use classes all the time: "Raipur" is an object of the class str, and [1, 2] is an object of the class list. The class keyword lets you write your own. This is the first example of the 2017 lesson.

Naming: class names use capital letters for each word, like Car and SavingsAccount. Variables and functions stay in lower case.

__init__ and self

__init__ is a special function that Python calls for you right after it makes a new object. Its job is to give the object its starting data. The values you pass when calling the class arrive as its parameters.

self is the object being worked on. Python passes it in for you as the first parameter, so Account(rishikesh, 5000) fills owner and balance, not self.

Concept: a name stored on an object, like account.balance, is called an attribute. You read and change it with a dot.

Each object has its own data

Attributes set through self are instance attributes. Every object gets its own copy, so changing one account does not touch another.

Concept: vars(obj) shows the instance attributes of an object as a dictionary. It is handy when you want to see what an object holds.

Class attributes are shared

A name assigned directly inside the class, outside any function, is a class attribute. There is one copy and every object sees it. Use it for a value that is the same for all objects, like the name of the bank.

Watch out: reading obj.bank looks on the object first and then on the class. Assigning obj.bank = ... always writes on the object. To change the shared value, assign on the class: Account.bank = ....

The shared list trap

A list or dictionary as a class attribute is shared too. If a method adds to it, every object sees the new item. This is almost never what you want.

The fix is to make the list inside __init__, so each object gets a new one.

Rule: values that can change in place (lists, dictionaries, sets) belong in __init__. Class attributes are for fixed values such as strings and numbers.

Methods

A function defined inside a class is called a method. It takes self first, so it can read and change the object it was called on. A method can return a value like any function, and it can call other methods through self.

Concept: sandhya.deposit(2000) is a short way to write Account.deposit(sandhya, 2000). That is where self comes from.

__str__ and __repr__

Printing a plain object gives something like <__main__.Account object at 0x10f3a2b50>, which tells you very little. Two special methods fix that. __str__ returns the friendly text that print() shows. __repr__ returns the exact text for developers, ideally the code that would rebuild the object.

Tip: if you write only one, write __repr__. Python uses it for print() as well when there is no __str__. Inside an f-string, !r asks for the repr of a value, which is why the name appears in quotes.

Inheritance

A class can be built on top of another class. The new class, called the child or subclass, gets every attribute and method of the parent and can add its own. Put the parent in brackets after the class name.

This is the inheritance example of the 2017 lesson. super() means "my parent class", so super().__init__(a, b) lets the parent set up its part of the object.

Overriding and super()

A child can also override a method: define one with the same name, and the child's version is used. Inside it, super().method() still reaches the parent's version, so you can add to the old behaviour without copying it.

A savings account is an account that earns interest and must keep a minimum balance.

Python 2: the old lesson wrote TwoNums.__init__(self, a, b). That still works, but super() is shorter and does not repeat the parent's name.

isinstance and issubclass

isinstance(obj, cls) asks whether an object was built from a class or from one of its children. issubclass(a, b) asks the same about two classes. Every class is a child of object, the parent of everything in Python.

Tip: prefer isinstance() over comparing type(). Code that accepts an Account should accept a SavingsAccount as well.

Class methods

A class method receives the class itself as its first parameter, named cls, in place of an object. Mark it with @classmethod. You call it on the class, before any object exists.

Its main use is a second way to build an object. Here an account is built from one line of text.

Why cls: the method calls cls(...), not Account(...). So when it is called on SavingsAccount it builds a SavingsAccount, with no extra code in the child.

Static methods

A static method receives neither self nor cls. It is a plain function that lives inside the class because it belongs to the same topic. Mark it with @staticmethod.

When to use each

KindFirst parameterUse it when
Method (the normal kind)self, the objectThe code reads or changes one object. This is the usual case.
@classmethodcls, the classThe code needs the class but no object yet, most often to build an object in another way.
@staticmethodnoneThe code needs neither. It is a helper that is kept in the class to stay near related code.

Properties

A property is a method that is used like an attribute, with no brackets. The method under @property is the getter: it runs when the value is read. An optional setter runs when the value is assigned, which is the place to check the new value.

Concept: raise stops with an error and try / except catches it. Both are explained on the next page. The real value is kept in _balance, a different name from the property, or the getter would call itself for ever.

Private by convention

Python has no truly private attributes. It has two naming habits. One leading underscore, _balance, tells other programmers "this is internal, please do not touch it from outside". Python does not enforce it.

Two leading underscores, __pin, make Python rename the attribute to _ClassName__pin behind the scenes. This is called name mangling. It stops a child class from reusing the name by accident. It is not a lock.

Tip: one underscore is enough in almost all code. Never rely on either form to hide a secret.

Comparing objects with __eq__

By default == on your own objects is true only when both sides are the very same object. Two accounts with the same data are still "not equal". Define __eq__ to say what equal means for your class.

Watch out: a class that defines __eq__ can no longer be put in a set or used as a dictionary key, unless it also defines __hash__.

Dataclasses: the short way

Many classes only hold a few values, and writing __init__, __repr__ and __eq__ for each one is repetitive. The @dataclass decorator writes all three for you from a list of field names and types.

Concept: the types after the colons are hints for readers and tools. Python does not check them when the program runs. field(default_factory=list) is the dataclass answer to the shared list trap: writing history: list = [] is refused with an error.

Quick reference

You want toWrite
Define a classclass Account:
Set up a new objectdef __init__(self, owner):
Make an objectaccount = Account("Sandhya Agrawani")
Store data on one objectself.balance = 0 inside a method
Share one value between all objectsbank = "AFB" directly in the class
Control what print() showsdef __str__(self): or def __repr__(self):
Build on another classclass SavingsAccount(Account):
Call the parent's versionsuper().withdraw(amount)
Check what an object isisinstance(obj, Account)
Build an object another way@classmethod with cls
Keep a helper inside the class@staticmethod
Check a value when it is assigned@property and @name.setter
Mark something as internalself._balance
Decide what == meansdef __eq__(self, other):
Get all of that with less typing@dataclass

What changed since Python 2

The original lesson was written for Python 2.7. If you meet old code, these are the differences that matter for classes.

Python 2.7 (2017 lesson)Python 3 (this page)
print "Name : ", self.nameprint("Name :", self.name)
class Car(object): was needed for a modern classclass Car: is enough, every class inherits from object
TwoNums.__init__(self, a, b)super().__init__(a, b)
super(ThreeNums, self).__init__(a, b)super().__init__(a, b)
No dataclasses@dataclass, since Python 3.7

Where to go next

The 2017 page is still online as it was written, with its Python 2.7 code: Pythofrank: Classes.

The property setter above stopped a bad value with raise. Continue with Python Errors and Files to see how errors are raised, caught and used.