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