相关疑难解决方法(0)

为什么我的类没有通过“def __int__”或“def _init_”初始化?为什么我会收到“不带参数”类型错误或属性错误?

如果您的问题作为此问题的重复项而被关闭,那是因为您有一个代码示例,其中包含以下任一内容:

class Example:
    def __int__(self, parameter):
        self.attribute = parameter
Run Code Online (Sandbox Code Playgroud)

或者:

class Example:
    def _init_(self, parameter):
        self.attribute = parameter
Run Code Online (Sandbox Code Playgroud)

当您随后尝试创建该类的实例时,会发生错误:

>>> Example("an argument")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Example() takes no arguments
Run Code Online (Sandbox Code Playgroud)

(在某些版本的 Python 中,错误可能会显示TypeError: object.__new__() takes no parameters。)

或者,该类的实例似乎缺少属性:

>>> class Example:
...     def __int__(self): # or _init_
...         self.attribute = 'value'

>>> Example().attribute
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Example' object has no …
Run Code Online (Sandbox Code Playgroud)

python initialization class typeerror magic-methods

11
推荐指数
1
解决办法
5733
查看次数

标签 统计

class ×1

initialization ×1

magic-methods ×1

python ×1

typeerror ×1