Python编程基础:第四十六节 super函数Super Function
生活随笔
收集整理的這篇文章主要介紹了
Python编程基础:第四十六节 super函数Super Function
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
第四十六節(jié) super函數(shù)Super Function
- 前言
- 實踐
前言
使用super函數(shù)可以在子類中直接調用父類的方法。通常情況下,我們會將一些通用的屬性或方法定義在父類中,子類可以直接使用父類中定義的方法。我們通過super函數(shù)便可將父類中定義的方法"拷貝"到子類中。
實踐
我們定義Variable用于存放子類用到的公共變量:
class Variable:def __init__(self, long, wide):self.long = longself.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()函數(shù)將父類中的__init__函數(shù)直接"拷貝"過來了,所以我們可以直接使用self.long、self.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 = highdef volume(self):return self.long * self.wide * self.high這里,我們首先通過super()函數(shù)將父類中的兩個變量引進,然后通過self.high = high定義我們新的變量high。然后通過函數(shù)volume求體積:
cube = Cube(3, 3, 3) print(cube.volume()) >>> 27最后添加一個小例子,大家分析一下計算結果:
class Variable:def __init__(self, long, wide):self.long = longself.wide = wideclass Square(Variable):def __init__(self, long, wide):super().__init__(long, wide)def area(self):return self.long * self.wideclass Cube(Square):def __init__(self, long, wide, high):super().__init__(long, wide)self.high = highdef volume(self, number):return super().area() * self.high * numbersquare = Square(2, 3) cube = Cube(3, 3, 3)print(square.area()) print(cube.volume(5)) >>> 6 >>> 135以上便是super函數(shù)的全部內容,感謝大家的收藏、點贊、評論。我們下一節(jié)將介紹抽象類(Abstract Classes),敬請期待~
總結
以上是生活随笔為你收集整理的Python编程基础:第四十六节 super函数Super Function的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python编程基础:第四十五节 方法链
- 下一篇: Python编程基础:第四十七节 抽象类