Python编程基础:第四十六节 super函数Super Function

第四十六节 super函数Super Function

前言

使用super函数可以在子类中直接调用父类的方法。通常情况下,我们会将一些通用的属性或方法定义在父类中,子类可以直接使用父类中定义的方法。我们通过super函数便可将父类中定义的方法"拷贝"到子类中。

实践

我们定义Variable用于存放子类用到的公共变量:

class Variable:
    def __init__(self, long, wide):
        self.long = long
        self.wide = wide

可见我们指定了长、宽两个变量。接下来我们定义子类Square,其继承于父类Variable。并使用父类中定义的变量:

class Square(Variable):
    def __init__(self, long, wide):
        super().__init__(long, wide)
        
    def area(self):
        return self.long * self.wide

可见我们的子类Square通过super()函数将父类中的__init__函数直接"拷贝"过来了,所以我们可以直接使用self.longself.wide这两个变量,并通过方法area求取面积:

square = Square(2, 3)
print(square.area())
>>> 6

我们有时候需要在父类的基础上添加新的内容,例如我们要求体积,那么还需要一个变量high

class Cube(Variable):
    def __init__(self, long, wide, high):
        super().__init__(long, wide)
        self.high = high
        
    def volume(self):
        return self.long * self.wide * self.high

这里,我们首先通过super()函数将父类中的两个变量引进,然后通过self.high = high定义我们新的变量high。然后通过函数volume求体积:

cube = Cube(3, 3, 3)
print(cube.volume())
>>> 27

最后添加一个小例子,大家分析一下计算结果:

class Variable:
    def __init__(self, long, wide):
        self.long = long
        self.wide = wide

class Square(Variable):
    def __init__(self, long, wide):
        super().__init__(long, wide)
        
    def area(self):
        return self.long * self.wide

class Cube(Square):
    def __init__(self, long, wide, high):
        super().__init__(long, wide)
        self.high = high
        
    def volume(self, number):
        return super().area() * self.high * number
    
square = Square(2, 3)
cube = Cube(3, 3, 3)

print(square.area())
print(cube.volume(5))
>>> 6
>>> 135

以上便是super函数的全部内容,感谢大家的收藏、点赞、评论。我们下一节将介绍抽象类(Abstract Classes),敬请期待~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值