在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ Python構(gòu)造函數(shù)
Python異常處理
Python循環(huán)
Python基本運(yùn)算符
Python網(wǎng)絡(luò)編程(Sockets)
Python可以開發(fā)哪些程序?
Python XML解析和處理
Python數(shù)字
Python函數(shù)
Python變量類型
Python os模塊方法
Python迭代器
Python安裝和環(huán)境配置
Python構(gòu)造函數(shù)
Python文件對象方法
Python日期和時(shí)間
Python的歷史
Python生成器
Python+MySQL數(shù)據(jù)庫操作(PyMySQL)
Python命令行參數(shù)
Python元組
Python發(fā)送郵件
Python列表
Python文件讀寫
Python教程
Python面向?qū)ο螅惡蛯ο螅?/span>
Python多線程編程
Python多重繼承
Python決策
Python是什么?
Python快速入門
Python繼承
Python字典
Python字符串
Python操作符重載
Python正則表達(dá)式
Python閉包
Python修飾器
Python功能特點(diǎn)
Python模塊

Python構(gòu)造函數(shù)

構(gòu)造函數(shù)是一種特殊類型的方法(函數(shù)),它在類的實(shí)例化對象時(shí)被調(diào)用。 構(gòu)造函數(shù)通常用于初始化(賦值)給實(shí)例變量。 構(gòu)造函數(shù)還驗(yàn)證有足夠的資源來使對象執(zhí)行任何啟動(dòng)任務(wù)。

創(chuàng)建一個(gè)構(gòu)造函數(shù)

構(gòu)造函數(shù)是以雙下劃線(__)開頭的類函數(shù)。構(gòu)造函數(shù)的名稱是__init__()

創(chuàng)建對象時(shí),如果需要,構(gòu)造函數(shù)可以接受參數(shù)。當(dāng)創(chuàng)建沒有構(gòu)造函數(shù)的類時(shí),Python會(huì)自動(dòng)創(chuàng)建一個(gè)不執(zhí)行任何操作的默認(rèn)構(gòu)造函數(shù)。

每個(gè)類必須有一個(gè)構(gòu)造函數(shù),即使它只依賴于默認(rèn)構(gòu)造函數(shù)。

舉一個(gè)例子:

創(chuàng)建一個(gè)名為ComplexNumber的類,它有兩個(gè)函數(shù)__init__()函數(shù)來初始化變量,并且有一個(gè)getData()方法用來顯示數(shù)字。

看這個(gè)例子:

#!/usr/bin/python3
#coding=utf-8

class ComplexNumber:

    def __init__(self, r = 0, i = 0):
        """"初始化方法"""
        self.real = r 
        self.imag = i 

    def getData(self):
        print("{0}+{1}j".format(self.real, self.imag))

if __name__ == '__main__':
    c = ComplexNumber(5, 6)
    c.getData()

執(zhí)行上面代碼,得到以下結(jié)果 -

5+6j

可以為對象創(chuàng)建一個(gè)新屬性,并在定義值時(shí)進(jìn)行讀取。但是不能為已創(chuàng)建的對象創(chuàng)建屬性。

看這個(gè)例子:

#!/usr/bin/python3
#coding=utf-8

class ComplexNumber:

    def __init__(self, r = 0, i = 0):
        """"初始化方法"""
        self.real = r 
        self.imag = i 

    def getData(self):
        print("{0}+{1}j".format(self.real, self.imag))

if __name__ == '__main__':
    c = ComplexNumber(5, 6)
    c.getData()

    c2 = ComplexNumber(10, 20)
    # 試著賦值給一個(gè)未定義的屬性
    c2.attr = 120
    print("c2 = > ", c2.attr)

    print("c.attr => ", c.attr)

執(zhí)行上面代碼,得到以下結(jié)果 -

5+6j
c2 = >  120
Traceback (most recent call last):
  File "D:\test.py", line 23, in <module>
    print("c.attr => ", c.attr)
AttributeError: 'ComplexNumber' object has no attribute 'attr'