How to call a Parent Class's method from Child Class in Python?

后端 未结 15 2385
無奈伤痛
無奈伤痛 2020-11-22 10:14

When creating a simple object hierarchy in Python, I\'d like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for

相关标签:
15条回答
  • 2020-11-22 10:52

    There's a super() in Python too. It's a bit wonky, because of Python's old- and new-style classes, but is quite commonly used e.g. in constructors:

    class Foo(Bar):
        def __init__(self):
            super(Foo, self).__init__()
            self.baz = 5
    
    0 讨论(0)
  • 2020-11-22 10:52

    This is a more abstract method:

    super(self.__class__,self).baz(arg)
    
    0 讨论(0)
  • 2020-11-22 10:56

    Use the super() function:

    class Foo(Bar):
        def baz(self, arg):
            return super().baz(arg)
    

    For Python < 3, you must explicitly opt in to using new-style classes and use:

    class Foo(Bar):
        def baz(self, arg):
            return super(Foo, self).baz(arg)
    
    0 讨论(0)
  • Many answers have explained how to call a method from the parent which has been overridden in the child.

    However

    "how do you call a parent class's method from child class?"

    could also just mean:

    "how do you call inherited methods?"

    You can call methods inherited from a parent class just as if they were methods of the child class, as long as they haven't been overwritten.

    e.g. in python 3:

    class A():
      def bar(self, string):
        print("Hi, I'm bar, inherited from A"+string)
    
    class B(A):
      def baz(self):
        self.bar(" - called by baz in B")
    
    B().baz() # prints out "Hi, I'm bar, inherited from A - called by baz in B"
    

    yes, this may be fairly obvious, but I feel that without pointing this out people may leave this thread with the impression you have to jump through ridiculous hoops just to access inherited methods in python. Especially as this question rates highly in searches for "how to access a parent class's method in Python", and the OP is written from the perspective of someone new to python.

    I found: https://docs.python.org/3/tutorial/classes.html#inheritance to be useful in understanding how you access inherited methods.

    0 讨论(0)
  • 2020-11-22 11:00
    class department:
        campus_name="attock"
        def printer(self):
            print(self.campus_name)
    
    class CS_dept(department):
        def overr_CS(self):
            department.printer(self)
            print("i am child class1")
    
    c=CS_dept()
    c.overr_CS()
    
    0 讨论(0)
  • 2020-11-22 11:00
    class a(object):
        def my_hello(self):
            print "hello ravi"
    
    class b(a):
        def my_hello(self):
        super(b,self).my_hello()
        print "hi"
    
    obj = b()
    obj.my_hello()
    
    0 讨论(0)
提交回复
热议问题