feat: class tutorials

This commit is contained in:
git-sandro 2026-02-26 12:25:16 +01:00
parent 6e5a0343f6
commit 0ea404ac01
5 changed files with 83 additions and 0 deletions

View File

@ -0,0 +1,10 @@
class Konto():
pass
k1 = Konto()
k2 = Konto()
print(k1)
print(k2)
print(k1 is k2)

View File

@ -0,0 +1,27 @@
from dataclasses import dataclass
@dataclass
class Student:
name: str
nr: int
sem: int
@dataclass
class Rechteck:
breite: float
hoehe: float
def flaeche(self) -> float:
return self.breite * self.hoehe
# Validierung
@dataclass
class Produkt:
name: str
preis: float
def __post_init__(self):
if not self.name:
raise ValueError("...")
if self.preis < 0:
raise ValueError("...")

21
class/konto.py Normal file
View File

@ -0,0 +1,21 @@
class Konto():
def __init__(self, inhaber, saldo):
if not inhaber:
raise ValueError("Inhaber darf nicht leer sein")
if saldo < 0:
raise ValueError("Saldo darf nicht negativ sein")
self.inhaber = inhaber
self.saldo = saldo
def einzahlen(self, betrag):
self.saldo += betrag
def abheben(self, betrag):
self.saldo -= betrag
k = Konto("Alice", 100)
print(k.saldo)
k.einzahlen(25)
print(k.saldo)
k.abheben(45)
print(k.saldo)

10
class/repr_tutorial.py Normal file
View File

@ -0,0 +1,10 @@
class Konto:
def __init__ ( self , inhaber , saldo ) :
self . inhaber = inhaber
self . saldo = saldo
def __repr__ ( self ) :
return f"Konto(inhaber = {self.inhaber!r}, saldo = {self.saldo!r})"
k = Konto ( " Alice " , 100.0)
print ( k ) # Konto ( inhaber = Alice , saldo =100.0)

15
class/str_tutorial.py Normal file
View File

@ -0,0 +1,15 @@
class Konto:
def __init__ (self, inhaber, saldo):
self.inhaber = inhaber
self.saldo = saldo
def __repr__(self):
return f"Konto(inhaber = {self.inhaber!r}, saldo = {self.saldo!r})"
def __str__(self):
return f"Konto von {self.inhaber}: CHF {self.saldo:.2f}"
k = Konto ( " Alice " , 100.0)
print(str(k)) # __str__
print(repr(k)) # __repr__
print(k) # bevorzugt __str__ , sonst __repr__