python對象初始化

來源:互聯網
上載者:User

標籤:move   ack   預設值   通過   使用者   .com   self   line   實現   

當python對象被建立以後,需要將對象進行初始化。Python有一個建構函式和一個初始化函數:

1、建構函式__new__,只接受一個參數,即類本身(它會在對象被構造之前調用,所以這裡也就沒有self參數),所以它返回剛被建立的對象。在日常編程中,很少被用到。

2、初始化函數__init__,常被用到。例如我們在Point類裡添加一個初始化函數,要求使用者在執行個體化Point對象的時候提供x和y參數。

class Point:    def __init__(self, x, y):        self.move(x, y)    def move(self,x, y):        self.x = x        self.y = y    def reset(self):        self.move(0, 0)#構造一個Pointpoint = Point(3, 5)print(point.x, point.y)# 3 5 

如果調用Point對象沒有含有合適的初始化參數時,會提示“沒有足夠的參數”等錯誤。如調用上述的Point類,運行如下

>>> a = Point(3)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: __init__() missing 1 required positional argument: ‘y‘>>> a = Point(3, 4, 5)Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: __init__() takes 3 positional arguments but 4 were given

如果不想讓兩個參數是必須的,通過將初始化函數設定為預設值來實現。如將上處的__init__的代碼修改如下:

class Point:    def __init__(self, x = 0, y = 0):        self.move(x, y)

 

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.