-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08-oop.py
More file actions
69 lines (54 loc) · 1.97 KB
/
Copy path08-oop.py
File metadata and controls
69 lines (54 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Student:
# by convention variables with prefix "_" are private
# "__" prefix is enforced by python
def __init__(self, first_name, last_name):
self.__first_name = first_name # assign input values
self.__last_name = last_name
self.__term = 1 # initial value not passed during initialization
def get_full_name(self):
return self.__first_name + " " + self.__last_name
def increase_term(self):
if self.__term >= 9:
return # no student shall have more than 9 terms
self.__term += 1
def get_term(self):
return str(self.__term)
# conversion to a string
def __str__(self):
return self.get_full_name() + " (" + self.get_term() + ". Term)"
# called when asked to represent itself
def __repr__(self):
return self.__str__()
class WorkingStudent(
Student
): # inherit from Student class (inherits all methods of base class (if not overwritten))
def __init__(self, first_name, last_name, company):
super().__init__(first_name, last_name) # call init function of base class
self.__company = company
def __str__(self):
return (
self.get_full_name()
+ " ("
+ self.get_term()
+ ". Term, "
+ self.__company
+ ")"
)
def main():
erik = Student("Erik", "Mustermann")
erik.increase_term()
erik.__term = "jkahs" # does not modify private variable, but much rather "mangles it" -- https://www.geeksforgeeks.org/python/private-variables-python/
print(erik)
erik # asked to represent itself
max = WorkingStudent("Max", "Müller", "DB AG")
print(max)
# return type of variable
print(type(erik))
print(type(max))
if type(erik) == Student:
print("Erik is a student")
if isinstance(max, Student):
# is instance can be used for asking for base class
print("Max is a Student")
if __name__ == "__main__":
main()