PyPython
IntermediateLesson 9 of 12

Classes & Object-Oriented Programming – Python

Custom data types with data and behavior.

A class is a blueprint for objects. __init__ is the constructor, self is the current object.

class Tier:
    def __init__(self, name):
        self.name = name

    def sprich(self):
        return f"{self.name} makes a sound"

class Hund(Tier):
    def sprich(self):
        return f"{self.name} says Woof!"

for t in [Tier("Something"), Hund("Rex")]:
    print(t.sprich())

With @dataclass you save a lot of boilerplate for pure data classes:

from dataclasses import dataclass

@dataclass
class Punkt:
    x: float
    y: float

p = Punkt(1.5, 2)
print(p, p.x)