|
| 1 | +class Parent: |
| 2 | + def __init__(self, first_name: str, last_name: str): |
| 3 | + self.first_name = first_name |
| 4 | + self.last_name = last_name |
| 5 | + |
| 6 | + def get_name(self) -> str: |
| 7 | + return f"{self.first_name} {self.last_name}" |
| 8 | + |
| 9 | + |
| 10 | +class Child(Parent): |
| 11 | + def __init__(self, first_name: str, last_name: str): |
| 12 | + # Call the parent class constructor |
| 13 | + super().__init__(first_name, last_name) |
| 14 | + self.previous_last_names = [] |
| 15 | + |
| 16 | + def change_last_name(self, last_name: str) -> None: |
| 17 | + self.previous_last_names.append(self.last_name) |
| 18 | + self.last_name = last_name |
| 19 | + |
| 20 | + def get_full_name(self) -> str: |
| 21 | + suffix = "" |
| 22 | + if len(self.previous_last_names) > 0: |
| 23 | + suffix = f" (née {self.previous_last_names[0]})" |
| 24 | + return f"{self.first_name} {self.last_name}{suffix}" |
| 25 | + |
| 26 | + |
| 27 | +person1 = Child("Elizaveta", "Alekseeva") |
| 28 | +print(person1.get_name()) # from Parent class |
| 29 | +print(person1.get_full_name()) # from Child class |
| 30 | + |
| 31 | +person1.change_last_name("Tyurina") |
| 32 | +print(person1.get_name()) |
| 33 | +print(person1.get_full_name()) |
| 34 | + |
| 35 | +person2 = Parent("Elizaveta", "Alekseeva") |
| 36 | +print(person2.get_name()) |
| 37 | + |
| 38 | +# The next lines will cause errors, because Parent doesn't have these methods |
| 39 | +# print(person2.get_full_name()) |
| 40 | +# person2.change_last_name("Tyurina") |
| 41 | + |
| 42 | +print(person2.get_name()) |
| 43 | +# print(person2.get_full_name()) |
| 44 | + |
| 45 | + |
| 46 | +# I learned that Parent and Child classes can have different methods — Parent can’t access methods only defined in Child |
| 47 | +# I understood that the child class can add new methods or override existing ones |
| 48 | + |
0 commit comments