標籤: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對象初始化