简体   繁体   中英

How can I add attributes to a derivated class?

class Human():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def hablar(self, message):
        print(message)


class Alien(Human):
    def __init__(self, planet):
        self.planet = planet

    def fly(self):
        print("I'm flying!")

This code is an example to show what I want to do. Imagine that I want an alien to inheritance all the properties of a Human but I also want him to have a planet attribute to distinguish from which planet does it comes.

When I do it as I did it in the mentioned code, it didn't work. Is it possible to do it? How?

Thanks!

You might want to refer to this question about calling parent class constructor from a child class.

You need to use the dunder method __init__ of the parent class inside the __init__ of Alien as so:

class Human():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def hablar(self, message):
        print(str(message))


class Alien(Human):

    def __init__(self, name, age, planet):
        super().__init__(name, age)
        self.planet = planet

    def fly(self):
        print("I'm flying!")

You need to reference the constructor of the parent class.

class Alien(Human):
    def __init__(self, name, age, planet):
        super().__init__(name, age)
        self.planet = planet
class Human():
    def __init__(self, name, age):
        self.name = name 
        self.age = age

class Alien(Human):
    def __init__(self, planet, **kwargs):
        self.planet = planet
        super(Alien, self).__init__(**kwargs)


Z = Alien(planet='Venus',name='Z',age=21)
print(Z.__dict__)

output:

{'planet': 'Venus', 'name': 'Z', 'age': 21}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM