python - Why can I not implement inheritance like this? -
this question has answer here:
to begin with, know there right way implement inheritance this:
class parent(): def __init__(self, last_name, eye_color): self.last_name = last_name self.eye_color = eye_color class child(parent): def __init__(self, last_name, eye_color, number_of_toys): parent.__init__(self, last_name, eye_color) self.number_of_toys = number_of_toys miley_cyrus = child("cyrus", "blue", 5) print(miley_cyrus.last_name) print(miley_cyrus.number_of_toys)
when run piece of code, there result that
cyrus 5
however when change 7th line :
self = parent(last_name, eye_color)
and the code has become:
class parent(): def __init__(self, last_name, eye_color): self.last_name = last_name self.eye_color = eye_color class child(parent): def __init__(self, last_name, eye_color, number_of_toys): self = parent(last_name, eye_color) self.number_of_toys = number_of_toys miley_cyrus = child("cyrus", "blue", 5) print(miley_cyrus.last_name) print(miley_cyrus.number_of_toys)
, run piece of code, there error indicates that:
traceback (most recent call last): file "/users/echo/documents/it/udacity/python/7.inheritance/inherentance.py", line 12, in <module> print(miley_cyrus.last_name) attributeerror: child instance has no attribute 'last_name'
what's wrong that? in advance.
i not sure doing can expected result way.
class parent(): def __init__(self, last_name, eye_color): self.last_name = last_name self.eye_color = eye_color class child(parent): def __init__(self, last_name, eye_color, number_of_toys): self.obj = parent(last_name, eye_color) self.number_of_toys = number_of_toys miley_cyrus = child("cyrus", "blue", 5) print(miley_cyrus.obj.last_name) print(miley_cyrus.number_of_toys)
self = parent
should self.some_variable = parent
Comments
Post a Comment