SW3-classes-ii #4
114
src/inheritance.py
Normal file
114
src/inheritance.py
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
|
||||||
|
|
||||||
|
class Speaker(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def speak(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Sleeper(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def sleep(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Dog(Speaker, Sleeper):
|
||||||
|
def speak(self):
|
||||||
|
print("Wau")
|
||||||
|
|
||||||
|
def sleep(self):
|
||||||
|
print("Zzzzz")
|
||||||
|
|
||||||
|
|
||||||
|
dog = Dog()
|
||||||
|
dog.speak()
|
||||||
|
dog.sleep()
|
||||||
|
|
||||||
|
|
||||||
|
class Storage(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def save(self, key: str, value: str) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def load(self, key: str) -> str:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MemoryStorage(Storage):
|
||||||
|
def __init__(self):
|
||||||
|
self.storage = {}
|
||||||
|
|
||||||
|
def save(self, key: str, value: str) -> None:
|
||||||
|
self.storage.update({key: value})
|
||||||
|
|
||||||
|
def load(self, key: str) -> str:
|
||||||
|
return self.storage.get(key)
|
||||||
|
|
||||||
|
|
||||||
|
storage: Storage = MemoryStorage()
|
||||||
|
storage.save("key", "value")
|
||||||
|
print(storage.load("key"))
|
||||||
|
|
||||||
|
|
||||||
|
class Person:
|
||||||
|
def __init__(self, name: str):
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
|
||||||
|
class Student(Person):
|
||||||
|
def __init__(self, name: str, semester: int):
|
||||||
|
super().__init__(name)
|
||||||
|
self.semester = semester
|
||||||
|
|
||||||
|
|
||||||
|
s = Student("Mein Name", 3)
|
||||||
|
print(s.name)
|
||||||
|
print(s.semester)
|
||||||
|
|
||||||
|
|
||||||
|
class A:
|
||||||
|
def ping(self) -> None:
|
||||||
|
print(" A ")
|
||||||
|
|
||||||
|
|
||||||
|
class B(A):
|
||||||
|
def ping(self) -> None:
|
||||||
|
print(" B ")
|
||||||
|
super().ping()
|
||||||
|
|
||||||
|
|
||||||
|
class C(A):
|
||||||
|
def ping(self) -> None:
|
||||||
|
print(" C ")
|
||||||
|
super().ping()
|
||||||
|
|
||||||
|
|
||||||
|
class D(B, C):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
D().ping()
|
||||||
|
|
||||||
|
|
||||||
|
class Animal(ABC):
|
||||||
|
@abstractmethod
|
||||||
|
def speak(self):
|
||||||
|
return "..."
|
||||||
|
|
||||||
|
def chorus(self, n: int):
|
||||||
|
if n <= 0:
|
||||||
|
raise ValueError(" n muss positiv sein ")
|
||||||
|
return " ".join(self.speak() for _ in range(n))
|
||||||
|
|
||||||
|
|
||||||
|
class Cat(Animal):
|
||||||
|
def speak(self):
|
||||||
|
return super().speak()
|
||||||
|
|
||||||
|
def chorus(self, n: int):
|
||||||
|
return super().chorus(n)
|
||||||
|
|
||||||
|
|
||||||
|
print(Cat().chorus(3))
|
||||||
Loading…
x
Reference in New Issue
Block a user