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.
the constructor, runs on
the object is passed automatically as
selfSymbols
| the 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.