|  | 
 
| 
感觉用不用init差不多,没什么区别,为什么init这个方法会更方便简单呢?
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  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())
 
 
__init__ 方法在实例化对象时候会自动调用,而且设置类的参数传入情况
 
 而如果你不用 __init__ 而用其他方法替代则必须先调用你定义的方法才能得到你期望的结果
 
 并且,不用 __init__ 就相当于默认没有参数,那么实例化类时候只能 Box() 不能加入多余参数
 
 就拿你这的代码举例子,假如我们不用 init 来初始化,代码就应该是这样:
 
 
 复制代码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())
 输出结果:
 
 
 
 | 
 |