首页 > 解决方案 > 为什么我在尝试使用 _init_ 时会出错?

问题描述

所以我只是想在我的 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

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

标签: pythonpython-3.xinitializationinit

解决方案


构造方法(与其他 Python魔术方法一样)被调用__init__(每边两个下划线)。


推荐阅读