鱼C论坛

 找回密码
 立即注册
查看: 1409|回复: 1

[已解决]类中__init__的用法

[复制链接]
发表于 2021-5-14 12:57:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
感觉用不用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())
最佳答案
2021-5-14 13:12:06

__init__ 方法在实例化对象时候会自动调用,而且设置类的参数传入情况

而如果你不用 __init__ 而用其他方法替代则必须先调用你定义的方法才能得到你期望的结果

并且,不用 __init__ 就相当于默认没有参数,那么实例化类时候只能 Box() 不能加入多余参数

就拿你这的代码举例子,假如我们不用 init 来初始化,代码就应该是这样:

  1. class Box:
  2.     def setDimension(self, width, height, depth):
  3.       self.width = width
  4.       self.height = height
  5.       self.depth = depth

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


  8. b = Box()
  9. b.setDimension(10, 20, 30) # 手动调用设置实例变量
  10. print(b.getVolume())
复制代码


输出结果:
  1. 6000
复制代码


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2021-5-14 13:12:06 | 显示全部楼层    本楼为最佳答案   

__init__ 方法在实例化对象时候会自动调用,而且设置类的参数传入情况

而如果你不用 __init__ 而用其他方法替代则必须先调用你定义的方法才能得到你期望的结果

并且,不用 __init__ 就相当于默认没有参数,那么实例化类时候只能 Box() 不能加入多余参数

就拿你这的代码举例子,假如我们不用 init 来初始化,代码就应该是这样:

  1. class Box:
  2.     def setDimension(self, width, height, depth):
  3.       self.width = width
  4.       self.height = height
  5.       self.depth = depth

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


  8. b = Box()
  9. b.setDimension(10, 20, 30) # 手动调用设置实例变量
  10. print(b.getVolume())
复制代码


输出结果:
  1. 6000
复制代码


想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-12 04:02

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表