fledgling 发表于 2021-5-14 12:57:58

类中__init__的用法

感觉用不用init差不多,没什么区别,为什么init这个方法会更方便简单呢?
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())

Twilight6 发表于 2021-5-14 13:12:06


__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())

输出结果:
6000

页: [1]
查看完整版本: 类中__init__的用法