2015-06-29 13 views
5

supponiamo che ho un po 'di codice Python:C'è un modo per usare super() per chiamare il metodo __init__ di ogni classe base in Python?

class Mother: 
    def __init__(self): 
     print("Mother") 

class Father: 
    def __init__(self): 
     print("Father") 

class Daughter(Mother, Father): 
    def __init__(self): 
     print("Daughter") 
     super().__init__() 

d = Daughter() 

Questo script stampa "Figlia". Esiste comunque la garanzia che tutti i metodi __init__ delle classi basi vengano chiamati? Un metodo che mi è venuta per fare questo è stato:

class Daughter(Mother, Father): 
    def __init__(self): 
     print("Daughter") 
     for base in type(self).__bases__: 
      base.__init__(self) 

Questo script stampa "Figlia", "Madre", "Padre". C'è un modo carino per farlo usando super() o un altro metodo?

risposta

5

Raymond Hettinger spiegato molto bene nel suo discorso Super Considered Super da PyCon 2015. La risposta è sì, se si progetta in questo modo, e chiamare super().__init__() in ogni classe

class Mother: 
    def __init__(self): 
     super().__init__() 
     print("Mother") 

class Father: 
    def __init__(self): 
     super().__init__() 
     print("Father") 

class Daughter(Mother, Father): 
    def __init__(self): 
     super().__init__() 
     print("Daughter") 

Il nome super è un peccato, è funziona davvero attraverso le classi base.

Problemi correlati