1 回答

TA貢獻1111條經(jīng)驗 獲得超0個贊
對于這樣一個常見問題,我希望大多數(shù)“int”對象沒有屬性變量問題要在這里解決。
這是我的嘗試。首先,這不是最好的表征:
'int' object has no attribute 'variable'
由于我看到的大多數(shù)示例都是以下形式:
'int' object has no attribute 'method'
并且是由調(diào)用int未實現(xiàn)的方法引起的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不與小數(shù)點混淆的情況下調(diào)用 an 方法:
>>> (128).bit_length()
8
>>>
但在大多數(shù)情況下,并不是有人試圖在 an 上調(diào)用方法,int而是 anint是針對另一種對象類型的消息的錯誤接收者。例如,這是一個常見錯誤:
TypeError: 'int' object has no attribute '__getitem__'
當(dāng)您嘗試對 an 進行下標時,會出現(xiàn)在 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.
如果您重用相同的變量名來保存不同類型的數(shù)據(jù),有時會發(fā)生這種情況——應(yīng)避免這種做法。
如果您收到類似的錯誤"AttributeError: 'int' object has no attribute 'append'",請考慮響應(yīng)什么類型的對象append()。Alist是,所以在我的代碼中的某個地方我調(diào)用append()了一個int我認為我有一個list.
添加回答
舉報