2016-06-07 10 views
6

Mam dwie klasy jedno rodzica i inne dziecko.Dodawanie dodatkowych funkcji do metody klasy nadrzędnej bez zmiany jej nazwy

class Parent(object): 

    def __init__(self): 
     #does something 

    def method_parent(self): 
     print "Parent" 

class Child(Parent): 

    def __init__(self): 
     Parent.__init__(self) 

    def method_parent(self): 
     print "Child" 

Po dziedziczenie rodzica Chcę zmodyfikować metodę Parent method_parent zachowaniem oryginalnego funkcjonalność tej metody i dodając kilka dodatkowych linijek kodu do tej metody.

wiem, że mogę stworzyć nową metodę jak

def method_child(self): 
    self.method_parent() 
    #Add extra lines of code to perform something 

Ale chcę używać oryginalnej nazwy metody. Nie mogę skopiować źródło dla tej metody, ponieważ metoda ta jest z C modułu

co chcę osiągnąć jest coś takiego

def method_parent(): 
    #do parent_method stuff 
    #do extra stuff 

Czy to w ogóle możliwe?

Odpowiedz

6

Zawsze można zadzwonić kod z rodzicem wykorzystaniem super() funkcję. Daje odniesienie do rodzica. Aby uzyskać połączenie parent_method(), należy użyć super().parent_method().

Oto fragment kodu (dla python3), który pokazuje, jak z niego korzystać.

class ParentClass: 
    def f(self): 
     print("Hi!"); 

class ChildClass(ParentClass): 
    def f(self): 
     super().f(); 
     print("Hello!"); 

W python2, trzeba zadzwonić Super dodatkowymi argumentami: super(ChildClass, self). Tak więc, fragment staną:

class ParentClass: 
    def f(self): 
     print("Hi!"); 

class ChildClass(ParentClass): 
    def f(self): 
     super(ChildClass, self).f(); 
     print("Hello!"); 

Jeśli zadzwonisz f() na wystąpienie ChildClass, to pokaże: „Hi Hello”.

Jeśli już kodowane w języku Java, jest to zasadniczo takie samo zachowanie. Możesz dzwonić super, gdzie chcesz. W metodzie, w funkcji init, ...

Są też inne sposoby zrobienia tego , ale jest mniej czysty. Na przykład:

ParentClass.f(self) 

Aby wywołać funkcję f klasy nadrzędnej.

4

Tak właśnie działa funkcja super.

class Child(Parent): 

    def __init__(self): 
     super(Child, self).__init__() 

    def method_parent(self): 
     super(Child, self).method_parent() 
     print "Child" 

W Pythonie 3, można zadzwonić super bez argumentów, jak super().method_parent()

1

można wywołać metodę nadrzędnej dokładnie taki sam sposób można stosować do jednej __init__:

class Child(Parent): 

    def __init__(self): 
     Parent.__init__(self) 

    def method_parent(self): 
     Parent.method_parent(self) # call method on Parent 
     print "Child" 

Ten jest, gdy chcesz jawnie wymienić klasę nadrzędną. Jeśli wolisz, możesz poprosić Pythona, aby dał kolejną klasę w celu uporządkowanego rozstrzygania metod, używając: super:

def method_parent(self): 
     super(Child, self).method_parent() # call method on Parent 
     print "Child" 
Powiązane problemy