class有兩種初始化形式
《python從零基礎到項目實踐》的筆記
>>>
1.在__init__ 里直接給出初始值,之后無法更改
1 class Box1(): 2 '''求立方體的體積''' 3 def __init__(self): 4 self.length = 0 5 self.width = 0 6 self.height = 0 7 def volume(self): 8 return self.length*self.width*self.height 9 B1 = Box1() 10 B1.length = 10 11 B1.weight = 10 12 B1.height = 10 13 print(B1.length) 14 print('%d'%(B1.volume()))
這里雖然第一個print的值是10,但是第二個print表示的體積的值仍然是0
2.在__init__ 里使用參數的方式初始化,之后可以更改
在定義屬性的時候,就給每個屬性初始化了,而每個初始化的值都是參數,也就是說這些值可以隨着參數改變,傳遞的。
1 class Box(): 2 def __init__(self,length1,width1,height1): 3 self.length = length1 4 self.width = width1 5 self.height = height1 6 7 def volume(self): 8 return self.width*self.length*self.height 9 10 box1 = Box(10, 10, 10) 11 box2 = Box(1, 2, 3) 12 print(box1.volume()) 13 print(box2.volume()) 14
這里第一個print的值是1000,第二個是6