Objekte und OO-Programmierung¶
# Ausgangslage
employees = {
"name 1": {
"salary": ...,
"skills": [...],
},
"name 2": {
"salary": ...,
"skills": [...],
},
...
}
In [ ]:
class Employee:
name = "Unknown"
gehalt = 0
skills = []
employee1 = Employee()
print(employee1.name)
print(employee1.gehalt)
print(employee1.skills)
employee2 = Employee()
print(employee2.name)
print(employee2.gehalt)
print(employee2.skills)
Unknown 0 [] Unknown 0 []
In [ ]:
employee1.name = "Joe Doe"
print(employee1.name)
print(employee2.name)
Joe Doe Unknown
In [ ]:
class Employee:
def __init__(self):
print("Init!")
employee3 = Employee()
Init!
In [ ]:
class Employee:
def __init__(self, name="", gehalt=0, skills=[]):
self.name = name
self.gehalt = gehalt
if skills is None:
self.skills = []
else:
self.skills = skills
employee4 = Employee("Joe Doe", 2000, [])
print(type(employee4))
print(employee4.name)
print(employee4.gehalt)
print(employee4.skills)#
employee5 = Employee("Jane Oh", 3000, ["marketing"])
print(employee5.name)
print(employee5.gehalt)
print(employee5.skills)
# Geht nicht, weil die Klasse kein Attribut "name" definiert
#print(Employee.name)
<class '__main__.Employee'> Joe Doe 2000 [] Jane Oh 3000 ['marketing']
In [ ]:
employee6 = Employee()
print(employee6.name)
print(employee6.gehalt)
print(employee6.skills)
0 []
In [ ]:
class Employee:
def __init__(self, name="", gehalt=0, skills=[]):
self.name = name
self.gehalt = gehalt
if skills is None:
self.skills = []
else:
self.skills = skills
def __str__(self):
s = [f"Employee '{self.name}'"]
s.append(f" gehalt: {self.gehalt}")
s.append(f" skills:")
for skill in self.skills:
s.append(f" - {skill}")
return "\n".join(s)
"""
Employee 'name':
gehalt: XXX
skills:
- skill 1
- skill 2
"""
employee7 = Employee(name="Bob Smith", skills=["software development", "it support"])
print(employee7)
Employee 'Bob Smith' gehalt: 0 skills: - software development - it support
In [ ]:
# Exkurs: Strings und `format()`
s = "Hallo, {}"
print(s.format("Welt"))
s = "{}, {}"
print(s.format("Guten Tag", "Welt"))
s = "{name}, {grussformel}"
print(s.format(grussformel="Guten Tag", name="Welt"))
grussformel="Guten Tag"
name="Welt"
print(f"{name}, {grussformel}")
def sagehallo(name):
# 'grussformel' ist eine globale variable!
print(f"{grussformel}, {name}")
sagehallo("Welt")
Hallo, Welt Guten Tag, Welt Welt, Guten Tag Welt, Guten Tag Guten Tag, Welt
In [ ]:
class Employee:
def __init__(self, name="", gehalt=0, skills=[]):
self.name = name
self.gehalt = gehalt
if skills is None:
self.skills = []
else:
self.skills = skills
def set_gehalt(self, neues_gehalt):
if not isinstance(neues_gehalt, int):
raise TypeError("gehalt muss ein Integer sein")
if neues_gehalt < 4000:
self.gehalt = neues_gehalt
else:
raise ValueError("Zu hohes gehalt!")
employee8 = Employee()
# Ok
employee8.gehalt = 5000
print(employee8.gehalt)
# ValueError!
employee8.set_gehalt(4000)
# TypeError!
employee8.set_gehalt("ein sack mehl")
5000
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /home/chris/work/python-kurs-softed/notebooks/objects.ipynb Cell 10 line 2 <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=21'>22</a> print(employee8.gehalt) <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=22'>23</a> # ValueError! ---> <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=23'>24</a> employee8.set_gehalt(4000) <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=24'>25</a> # TypeError! <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=25'>26</a> employee8.set_gehalt("ein sack mehl") /home/chris/work/python-kurs-softed/notebooks/objects.ipynb Cell 10 line 1 <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=14'>15</a> self.gehalt = neues_gehalt <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=15'>16</a> else: ---> <a href='vscode-notebook-cell:/home/chris/work/python-kurs-softed/notebooks/objects.ipynb#X12sZmlsZQ%3D%3D?line=16'>17</a> raise ValueError("Zu hohes gehalt!") ValueError: Zu hohes gehalt!