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): File "<stdin>", line 1, in <module>AttributeError: 'int' object has no attribute 'length'>>> 该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']>>> 你可以打电话给他们:>>> help(int.bit_length)Help on method_descriptor:bit_length(...) int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6>>> 这向我们展示了如何在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): File "<stdin>", line 1, in <module>TypeError: 'int' object has no attribute '__getitem__'>>> Python3 提供了更有用的信息,TypeError: 'int' object is not subscriptable.如果您重用相同的变量名来保存不同类型的数据,有时会发生这种情况——应避免这种做法。如果您收到类似的错误"AttributeError: 'int' object has no attribute 'append'",请考虑响应什么类型的对象append()。Alist是,所以在我的代码中的某个地方我调用append()了一个int我认为我有一个list.