【问题标题】:Can someone please explain what is the difference between __init or __init__ (one has only two underscores before and the other has four underscores)?有人可以解释一下 __init 或 __init__ 有什么区别(一个之前只有两个下划线,另一个有四个下划线)?
【发布时间】:2021-04-09 00:18:31
【问题描述】:

第一个

class Animal():
    def __init(self, name):
        self.name = name
    def talk(self):
        pass

另一个:

class Rectangle():
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def getArea(self):
        print(self.length*self.breadth, "is area of Rectangle")

【问题讨论】:

标签: python methods init


【解决方案1】:

就第一个而言,我不确定我是否在任何地方见过它,但对于第二个,__init__ 是 python 类中的保留方法。它在面向对象的术语中称为构造函数。当从类创建对象时调用此方法,它允许类初始化类的属性。更多信息请查看this链接

【讨论】:

    【解决方案2】:

    看来我很困惑,我正在上 python 课程,这似乎只是类中定义的名称,init 是可以理解的..

    感谢您的宝贵时间,非常感谢您的回答! 花了我 30 分钟或搜索不存在的东西是我的错…… 我的坏...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-21
      • 2010-12-21
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      相关资源
      最近更新 更多