What's the difference between super().method() and self.method()

后端 未结 2 1955
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 03:23

What\'s the difference between using super().method() and self.method(), when we inherit something from a parent class and why use one instead of anoth

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 04:12

    self

    self, which is mostly used as the first parameter of instance methods of classes, always represents the calling object/instance of the class.

    super()

    super() refers to object of parent class. It is useful in case of method overriding and this is in case of numerous programming languages including C++, Java etc. In Java, super() is used to call the constructor of parent class.

    Please have a look at the below little example.

    class TopClass(object):
        def __init__(self, name, age):
            self.name = name;
            self.age = age;
    
        def print_details(self):
            print("Details:-")
            print("Name: ", self.name)
            print("Age: ", self.age)
            self.method()
    
        def method(self):
            print("Inside method of TopClass")
    
    class BottomClass(TopClass):
        def method(self):
            print("Inside method of BottomClass")    
    
        def self_caller(self):
             self.method()
    
        def super_caller(self):
             parent = super()
             print(parent)
             parent.method()
    
    child = BottomClass ("Ryan Holding", 26)
    child.print_details()
    
    """
    Details:-
    Name:  Ryan Holding
    Age:  26
    Inside method of BottomClass
    """
    
    parent = TopClass("Rishikesh Agrawani", 26)
    parent.print_details()
    
    """
    Details:-
    Name:  Rishikesh Agrawani
    Age:  26
    Inside method of TopClass
    """
    
    child.self_caller()
    child.super_caller()
    
    """
    Inside method of BottomClass
    , >
    Inside method of TopClass
    """
    

提交回复
热议问题