-3
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!

3vts
  • 778
  • 1
  • 12
  • 25

3 Answers3

1

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!")
Raphaele Adjerad
  • 1,117
  • 6
  • 12
1

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
Jake Tae
  • 1,681
  • 1
  • 8
  • 11
1
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}
Qsnok
  • 43
  • 5