Python inheritance: How can I update a parent attribute when creating a child's subclass? -


trying understand multiple inheritance.

i have created parent class called 'human' , created child class called 'man'. child class inherits attributes , methods except human_gender attribute overwritten , set 'male'. - works fine , expected.

what tried created new child class called 'boychild' (from 'man') hoped inherit of man's attributes , methods except wished overwrite age attribute set age 8. throwing error.

why error occurring? if remove 'age=8' super().init parentheses, inherits normal, can't seem overwrite inherited class' attribute 'age'.

class human():     '''this human class'''     def __init__(self, human_gender = "unknown", age = 0,                     hunger_level=0):         self.human_gender = human_gender         self.age = age         self.hunger_level = hunger_level      def setgender(self):         self.human_gender = input("please enter human's gender:")      def setage(self):         self.age = int(input("please enter human's age"))      def sethunger_level(self):         self.hunger_level = int(input("please enter human's hunger level (0-10)"))  class man(human):     '''this man class'''     def __init__(self):         super().__init__(human_gender="male")  class boychild(man):     '''this boychild class'''     def __init__(self):         super().__init__(age=8)   guy = boychild() #guy.setgender() #guy.setage() guy.sethunger_level() print("the human a: ", guy.human_gender) print("the human is: ", guy.age) print("the human's hunger level is: ", guy.hunger_level)  input() 

the __init__ method of man doesn't accept keyword arguments @ all. since rely on work, should use them:

class man(human):     '''this man class'''     def __init__(self, **kwargs):         super().__init__(human_gender="male", **kwargs)  class boychild(man):     '''this boychild class'''     def __init__(self, **kwargs):         super().__init__(age=8, **kwargs) 

this way catch every argument not handled class , passt on.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -