【发布时间】:2023-02-08 09:41:42
【问题描述】:
如果您的问题作为此问题的副本而被关闭,那是因为您有一个代码示例,其中包含以下任一内容:
class Example:
def __int__(self, parameter):
self.attribute = parameter
或者:
class Example:
def _init_(self, parameter):
self.attribute = parameter
当您随后尝试创建该类的实例时,会发生错误:
>>> Example("an argument")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Example() takes no arguments
或者,该类的实例似乎缺少属性:
>>> 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 attribute 'attribute'
您可能还想知道:这些异常消息是什么意思,它们与问题有什么关系?为什么没有更早出现问题,例如,类定义本身?问题还可能如何表现?以后如何防范这个问题?
这是一人工规范重复专门为避免新 Python 程序员编写的代码中的两个最常见的印刷错误而创建。虽然由拼写错误引起的问题通常会因此而关闭,但在这种情况下有一些有用的东西需要解释,并且有一个重复的目标可以更快地关闭问题。我试图将问题设计为易于搜索。
【问题讨论】:
标签: python class initialization typeerror magic-methods