Python中__init__的用法和理解


在Python中定義類經常會用到__init__函數(方法),首先需要理解的是,兩個下划線開頭的函數是聲明該屬性為私有,不能在類的外部被使用或訪問。而__init__函數(方法)支持帶參數類的初始化,也可為聲明該類的屬性(類中的變量)。__init__函數(方法)的第一個參數必須為self,后續參數為自己定義。

從文字理解比較困難,通過下面的例子能非常容易理解這個概念:

例如我們定義一個Box類,有width, height, depth三個屬性,以及計算體積的方法:

#!/usr/bin/python
# -*- coding utf-8 -*-
#Created by Lu Zhan

class Box:
def setDimension(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth

def getVolume(self):
return self.width * self.height * self.depth

b = Box()
b.setDimension(10, 20, 30)
print(b.getVolume())

 


我們在Box類中定義了setDimension方法去設定該Box的屬性,這樣過於繁瑣,而用__init__()這個特殊的方法就可以方便地自己對類的屬性進行定義,__init__()方法又被稱為構造器(constructor)。

#!/usr/bin/python
# -*- coding utf-8 -*-
#Created by Lu Zhan

class Box:
#def setDimension(self, width, height, depth):
# self.width = width
# self.height = height
# self.depth = depth
def __init__(self, width, height, depth):
self.width = width
self.height = height
self.depth = depth

def getVolume(self):
return self.width * self.height * self.depth

b = Box(10, 20, 30)
print(b.getVolume())

 


 
---------------------

來源:https://blog.csdn.net/luzhan66/article/details/82822896


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM