python - AttributeError: 'child' object has no attribute '_name' -
i'm beginner python , trying understand class inheritance. when try following code error :
attributeerror: 'child' object has no attribute '_name'
and here's code :
class parent: def __init__(self): self._name = "smith" @property def name(self): return self._name class child(parent): def __init__(self, childname): self._childname = childname def getname(self): return "child : {} .. parent : {}".format(self._childname, super().name) def main(): dad = parent() son = child("jack") print(son.getname()) if __name__ == "__main__": main()
why ? understanding class inheritance in python correctly ?
your problem occurs here:
def getname(self): return "child : {} .. parent : {}".format(self._childname, super().name)
to more precise, super().name
culprit: not super()
useless , shall have called name()
instead of name
, if @ code of name()
, notice uses variable _name
.
however, _name
initialized in parent's __init__
method. if want called, should call parent __init__
method in child's one, not done automagically. child __init__
method should be:
class child(parent): def __init__(self, childname): super().__init__() self._childname = childname
Comments
Post a Comment