All courses › Intermediate Programming › Classes and __init__

Classes and __init__

A class is a template for creating objects. __init__ is the constructor: it runs automatically when you create a new object, and sets up the attributes. self inside a method refers to the object the method is called on.

class K: def __init__(self,…)\text{class } K: \ \text{def }\_\_\text{init}\_\_(\text{self}, \ldots)the constructor, runs on K(…)K(\ldots)
obj.method()≡K.method(obj)\text{obj.method}() \equiv K.\text{method}(\text{obj})the object is passed automatically as self

Symbols

selfselfthe object (instance) itself

Example

class Rektangel:

def __init__(self, b, h): self.b, self.h = b, h

def areal(self): return self.b * self.h

Rektangel(8, 4).areal() gives 32.

self is just a name, but follow the convention — Python fills it in automatically regardless of what you call it.
Practise object orientation for free →

Inheritance and super() →

Part of Intermediate Programming: Object orientation.