Python 中 AttributeError: Int object Has No Attribute 错误

The int data type is one of the most basic and primitive data types and is used to store and represent integers not only in Python but also in several other programming languages. The int data type can store any positive or negative integer as long as there is no decimal point.

This article highlights and provides a solution to a specific error that can occur when we use the int data type in Python.


Fix Python error AttributeError: ‘int’ object has no attribute

AttributeError is one of the common errors that can occur in Python code. This tutorial handles an AttributeError where the 'int' object has no attribute 'A'.

Here, A can be any function used on an int object.

Before proceeding with the sample code and learning how to eliminate this error, let us understand the reasons behind the occurrence of this error.

AttributeError: ‘int’ object has no attribute occurs in code when you try to access an attribute that should not be accessed using an integer.

Let us consider a sample code, in this case we have a property as startswith() function and try to use it with a variable having int data type.

x = 16
print(type(x))
y = x.startswith('1')
print(y)

The above code provides the following output.

Fix Python error AttributeError int object has no attribute

We know that startswith() the function is a property of string data type and not an int data type, it is easy to understand why this error occurs and how to solve it in our case.

The above error can be eliminated if you convert the int data type variable to str data type and then process the given startswith() attribute.

The following code converts a variable of int data type to str data type and then processes the given startswith() attribute.

x = 16
print(type(x))
y = str(x).startswith('1')
print(y)

The above code provides the following output.

<class 'int'>
True

おすすめ

転載: blog.csdn.net/fengqianlang/article/details/134741267