|
| 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 | + super().__init__(first_name, last_name) |
| 13 | + self.previous_last_names = [] |
| 14 | + |
| 15 | + def change_last_name(self, last_name) -> None: |
| 16 | + self.previous_last_names.append(self.last_name) |
| 17 | + self.last_name = last_name |
| 18 | + |
| 19 | + def get_full_name(self) -> str: |
| 20 | + suffix = "" |
| 21 | + if len(self.previous_last_names) > 0: |
| 22 | + suffix = f" (née {self.previous_last_names[0]})" |
| 23 | + return f"{self.first_name} {self.last_name}{suffix}" |
| 24 | + |
| 25 | +person1 = Child("Elizaveta", "Alekseeva") |
| 26 | +print(person1.get_name()) |
| 27 | +print(person1.get_full_name()) |
| 28 | +person1.change_last_name("Tyurina") |
| 29 | +print(person1.get_name()) |
| 30 | +print(person1.get_full_name()) |
| 31 | + |
| 32 | +person2 = Parent("Elizaveta", "Alekseeva") |
| 33 | +print(person2.get_name()) |
| 34 | +#print(person2.get_full_name()) |
| 35 | +#person2.change_last_name("Tyurina") |
| 36 | +print(person2.get_name()) |
| 37 | +#print(person2.get_full_name()) |
| 38 | + |
| 39 | +# Output for person1: |
| 40 | +#1. line 26 it call the method get_name() from the Parent class the output will be "Elizaveta Alekseeva" as the Child class in inheriting the properties from the Parent class. |
| 41 | +#2. line 27 it call the get_full_name() method from the Child class the output will be "Elizaveta Alekseeva " as the check statement will get skip entirely. |
| 42 | +#3. line 28 we call the change_last_name() method to change last name of person1, the method started as an empty array then it append (end of the array)to it the new parameter value given output "Elezaveta Tyurina". CORRECTION: it will append the old last_name |
| 43 | +#4. I think that line 29 and 30 will print as the 26 and 27, as they do not interact with the new array created by change_last_name method(). CORRECTION: line 30 the list now have leng 1, means it will add suffix value at the end. |
| 44 | + |
| 45 | +#Output for person2: |
| 46 | +#1. line 33 and 36 the output will be similar to line 26 |
| 47 | +#2. lines 34, 35, 37 all they will throw an error as the inheritance work as waterfall a child can access parent methods, however a parent class can not. |
0 commit comments