“'int'对象没有属性'变量'”的常见原因?

看到有关 Stack Overflow 的许多问题'int' object has no attribute 'variable'仅针对此类主题错误消息的特定场景过于具体,我想知道在涉及此类错误消息的任何给定场景中我需要重新检查的代码方面。

简单地说,这个网络上没有一个问题要求对所述错误消息进行广泛的推理,我想这里有相当多的读者更愿意研究这些类型的问题,因为这是一种常见的情况这里的用户提出了同样的问题,但问题和答案对于该特定领域过于具体而没有任何用处。总的来说,该站点上的许多类似问题都过于针对某人代码的特定上下文。

我想确保回答这个问题的答案几乎可以回答有关所述错误消息的任何给定情况。对于这样一个常见问题,我希望'int' object has no attribute variable在这里解决大部分问题。


狐的传说
浏览 457回答 1
1回答

catspeake

对于这样一个常见问题,我希望大多数“int”对象没有属性变量问题要在这里解决。这是我的尝试。首先,这不是最好的表征:'int' object has no attribute 'variable'由于我看到的大多数示例都是以下形式:'int' object has no attribute 'method'并且是由调用int未实现的方法引起的int:>>> x = 4>>> x.length()Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>AttributeError: 'int' object has no attribute 'length'>>>&nbsp;该int班确实有方法:>>> dir(int)['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__','__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__','__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__','__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__','__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__','__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__','__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__','__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__','__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__','__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator','from_bytes', 'imag', 'numerator', 'real', 'to_bytes']>>>&nbsp;你可以打电话给他们:>>> help(int.bit_length)Help on method_descriptor:bit_length(...)&nbsp; &nbsp; int.bit_length() -> int&nbsp; &nbsp; Number of bits necessary to represent self in binary.&nbsp; &nbsp; >>> bin(37)&nbsp; &nbsp; '0b100101'&nbsp; &nbsp; >>> (37).bit_length()&nbsp; &nbsp; 6>>>&nbsp;这向我们展示了如何在int不与小数点混淆的情况下调用 an 方法:>>> (128).bit_length()8>>>但在大多数情况下,并不是有人试图在 an 上调用方法,int而是 anint是针对另一种对象类型的消息的错误接收者。例如,这是一个常见错误:TypeError: 'int' object has no attribute '__getitem__'当您尝试对 an 进行下标时,会出现在 Python2 中int:>>> x = 4>>> x[0]Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>TypeError: 'int' object has no attribute '__getitem__'>>>&nbsp;Python3 提供了更有用的信息,TypeError: 'int' object is not subscriptable.如果您重用相同的变量名来保存不同类型的数据,有时会发生这种情况——应避免这种做法。如果您收到类似的错误"AttributeError: 'int' object has no attribute 'append'",请考虑响应什么类型的对象append()。Alist是,所以在我的代码中的某个地方我调用append()了一个int我认为我有一个list.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python