I'm trying to create a subclass in a particular case and I can not attach attributes or method to it. I think the new / init usage is not clear to me but I could not find ways to do that from the internet.
Here is a minimal working toy example showing what I am trying to do.
# I have this
class Human():
def __init__(self):
self.introduction = "Hello I'm human"
def create_special_human():
special_human = Human()
do_very_complicated_stuffs(special_human)
special_human.introduction = "Hello I'm special"
return special_human
# I want to create this class
class SuperHero(Human):
def __new__(self):
special_human = create_special_human()
return special_human
def __init__(self):
self.superpower = 'fly'
def show_off(self):
print(self.introduction)
print(f"I can {self.superpower}")
human = Human()
special_human = create_special_human()
super_hero = SuperHero()
super_hero.show_off() # fails with error "type object 'Human' has no attribute 'show_off'"
print(super_hero.superpower) # fails with error "type object 'Human' has no attribute 'superpower'"
I want to create the subclass Superhero
, and I need to initialize it with what is returned by create_special_human()
, because this function is very complex in the real case. Moreover, I can not modify the Human
class and create_special_human()
.
I am aware that the returned type is Human, which is wrong, but I don't know why that happens.
Aucun commentaire:
Enregistrer un commentaire