Advanced object-oriented: Possible solution for Eye Color Exercise
class Eye:
def __init__(self, color):
self.color = color
class Mother(Eye):
def __init__(self, color):
super().__init__(color)
class Father(Eye):
def __init__(self, color):
super().__init__(color)
class Child(Eye):
def __init__(self, mom: Mother, dad: Father):
result = "blue"
if "brown" in [mom.color, dad.color]:
result = "brown"
super().__init__(result)
mom = Mother("blue")
dad = Father("blue")
kid = Child(mom, dad)
Thanks @HaBeSte! Could you just add a brief description of the reason behind this suggestion?
I would probably suggest to create a Human class instead with some "default" attributes. Otherwise this becomes more an example of "composition" rather than "inheritance".
Composition would be natural in this case:
class Mother:
def __init__(self, eye_color: str):
self.eye_color = eye_color
class Father:
def __init__(self, eye_color: str):
self.eye_color = eye_color
class Child:
def __init__(self, mother: Mother, father: Father):
self.mother = mother
self.father = father
self.eye_color = self.set_eye_color()
def set_eye_color(self):
"""Set Child eye color based on Mother and Father eye color"""
return self.mother.eye_color + self.father.eye_color
m = Mother("blu")
f = Father("green")
print(Child(m, f).eye_color)
Hi @edoardob90 As I understood the idea behind the task was to see the inheritance as an example, using an example where in real life inheritance played a role. The initial solution bothered me a bit, since it used variables called mother_eye_color, resp. father_eye_color and super() couldn't be used directly, because of the double inheritance. So I sat together with @despadam and we came up with the solution above. I see your point, when we use "eye" (or human) for inheritance, again it's not really the inheritance from mom and dad as it initially supposed to be the idea. maybe a class called "genes" would make more sense in that context?