python中初始化執行個體屬性

來源:互聯網
上載者:User

標籤:person   怎麼辦   typeerror   使用   數位   int   traceback   用法   初學   

雖然我們可以自由地給一個執行個體綁定各種屬性,但是,現實世界中,一種類型的執行個體應該擁有相同名字的屬性。例如,Person類應該在建立的時候就擁有 name、gender 和 birth 屬性,怎麼辦?

在定義 Person 類時,可以為Person類添加一個特殊的__init__()方法,當建立執行個體時,__init__()方法被自動調用,我們就能在此為每個執行個體都統一加上以下屬性:

class Person(object):    def __init__(self, name, gender, birth):        self.name = name        self.gender = gender        self.birth = birth

__init__() 方法的第一個參數必須是 self(也可以用別的名字,但建議使用習慣用法),後續參數則可以自由指定,和定義函數沒有任何區別。

相應地,建立執行個體時,就必須要提供除 self 以外的參數:

xiaoming = Person(‘Xiao Ming‘, ‘Male‘, ‘1991-1-1‘)xiaohong = Person(‘Xiao Hong‘, ‘Female‘, ‘1992-2-2‘)

有了__init__()方法,每個Person執行個體在建立時,都會有 name、gender 和 birth 這3個屬性,並且,被賦予不同的屬性值,訪問屬性使用.操作符:

print xiaoming.name# 輸出 ‘Xiao Ming‘print xiaohong.birth# 輸出 ‘1992-2-2‘

要特別注意的是,初學者定義__init__()方法常常忘記了 self 參數:

>>> class Person(object):...     def __init__(name, gender, birth):...         pass... >>> xiaoming = Person(‘Xiao Ming‘, ‘Male‘, ‘1990-1-1‘)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: __init__() takes exactly 3 arguments (4 given)

這會導致建立失敗或運行不正常,因為第一個參數name被Python解譯器傳入了執行個體的引用,從而導致整個方法的調用參數位置全部沒有對上。

樣本:

定義Person類的__init__方法,除了接受 name、gender 和 birth 外,還可接受任意關鍵字參數,並把他們都作為屬性賦值給執行個體。

class Person(object):    def __init__(self,name,gender,birth,**kw):        self.name=name        self.gender=gender        self.birth=birth        self.kw=kwxiaoming = Person(‘Xiao Ming‘, ‘Male‘, ‘1990-1-1‘, job=‘Student‘)print xiaoming.nameprint xiaoming.kw

 結果:

Xiao Ming{‘job‘: ‘Student‘}

 

python中初始化執行個體屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.