how to refer to a parent method in python?

This question already has an answer here:

  • Call a parent class's method from child class in Python? 12 answers

  • If you know you want to use A you can also explicitly refer to A in this way:

    class B(A):
        def f(self,num): 
            return 7 * A.f(self,num)
    

    remember you have to explicitly give the self argument to the member function Af()


    Use super :

    return 7 * super(B, self).f(num)
    

    Or in python 3, it's just:

    return 7 * super().f(num)
    

    In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

    Python-2.x

    class A(object):
     def __init__(self):
       print "world"
    
    class B(A):
     def __init__(self):
       print "hello"
       super(B, self).__init__()
    

    Python-3.x

    class A(object):
     def __init__(self):
       print "world"
    
    class B(A):
     def __init__(self):
       print "hello"
       super().__init__()
    

    super() is now equivalent to super(<containing classname>, self) as per the docs.

    链接地址: http://www.djcxy.com/p/30048.html

    上一篇: 在JavaScript中使用'原型'与'这个'?

    下一篇: 如何在python中引用父方法?