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

后端 未结 15 2586
無奈伤痛
無奈伤痛 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 11:03

    In this example cafec_param is a base class (parent class) and abc is a child class. abc calls the AWC method in the base class.

    class cafec_param:
    
        def __init__(self,precip,pe,awc,nmonths):
    
            self.precip = precip
            self.pe = pe
            self.awc = awc
            self.nmonths = nmonths
    
        def AWC(self):
    
            if self.awc<254:
                Ss = self.awc
                Su = 0
                self.Ss=Ss
            else:
                Ss = 254; Su = self.awc-254
                self.Ss=Ss + Su   
            AWC = Ss + Su
            return self.Ss
    
    
        def test(self):
            return self.Ss
            #return self.Ss*4
    
    class abc(cafec_param):
        def rr(self):
            return self.AWC()
    
    
    ee=cafec_param('re',34,56,2)
    dd=abc('re',34,56,2)
    print(dd.rr())
    print(ee.AWC())
    print(ee.test())
    

    Output

    56
    
    56
    
    56
    

提交回复
热议问题