【问题标题】:Why do I get an error when trying to use _init_?为什么我在尝试使用 _init_ 时会出错?
【发布时间】:2018-12-12 07:06:41
【问题描述】:

所以我只是尝试在我的 Python 3.7.0 IDLE (Shell) 中从 python.org 执行相同的基本类示例,并且当我尝试运行此代码时:

class Giraffes:
    def _init_(self, spots):
        self.giraffe_spots = spots

gerald = Giraffes(100)

它给了我这个错误:

Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
  gerald = Giraffes(100)
TypeError: Giraffes() takes no arguments

Giraffes 类中的 init 函数不是让 Gerald 接受参数 self 吗?

【问题讨论】:

    标签: python python-3.x initialization init


    【解决方案1】:

    constructor method(与其他 Python magic methods 一样)称为 __init__(两边各有两个下划线)。

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多