python(python中的super函式、)

yytkkn發表於2020-12-27

學習目標:

Python學習十七、


學習內容:

1、python中的super函式


1、python中的super函式

在python中,類裡的__init__方法(函式)和屬性,在類例項化的時候會被自動執行
在類的繼承當中可能覆蓋同名的方法,這樣就不能呼叫父類的方法了,只能呼叫子類的構造方法

  • super函式:呼叫父類或者超類的方法(函式)和屬性
  • super(super所在的類名,self).屬性或者父類(超類)的方法(函式)和屬性:這是python2.x中的寫法
  • super().屬性或者父類(超類)的方法(函式)和屬性:這是python3.x中的寫法,同時相容2.x的寫法
class person():

    

def __init__(self):
        print('你出生啦!!!')

    def say(self):
        print('hello the world!!!')


class student(person):

    def __init__(self,sex,name):
        super().__init__()
        self.sex = sex
        self.name = name
        print('%s %s你上學啦!!!'%(sex,name))

    def getName(self):
        return self.name

    def say(self):
        super().say()
        print('hello my school!!!')


st = student('man','小明')
print(st.getName())
st.say()
輸出:
你出生啦!!!
man 小明你上學啦!!!
小明
hello the world!!!
hello my school!!!
  • super()函式呼叫父類的父類(超類)類跨過三代的方法(函式)和屬性
class person():

    def __init__(self):
        print('你出生啦!!!')

    def say(self):
        print('hello the world!!!')
    def runs(self):
        print('you can run')

class student(person):
    def __init__(self,sex,name):
        self.sex = sex
        self.name = name

    def getName(self):
        return self.name

    def say(self):
        super().say()
        print('hello my school!!!')

class myrun(student):
    def runs(self):
        super().runs()
        print('you can run fast')

runss = myrun('man','xioaming')
runsss = runss.runs()
輸出:
you can run
you can run fast

相關文章