Tutorial Study Image

Python int()

int() 函数用于将给定值转换为整数。结果整数值始终为基数 10。如果我们将 int() 与自定义对象一起使用,则会调用对象的 __int__() 函数。


int(x=0, base=10)# Where x can be Number or string

int() 参数

接受 2 个参数,其中第一个参数 'x' 的默认值为 0。第二个参数 'base' 的默认值为 10,也可以是 0(代码文字)或 2-36。

参数 描述 必需/可选
x 要转换为整数对象的数字或字符串。 必需
base x 中数字的基数 可选

int() 返回值

输入 返回值
整数对象 基数为 10
无参数 返回 0
如果给定基数 在给定的基数中(0, 2, 8, 10, 16)

Python 中 int() 方法的示例

示例 1:int() 在 Python 中如何工作?


# integer
print("int(123) is:", int(123))

# float
print("int(123.23) is:", int(123.23))

# string
print("int('123') is:", int('123'))
 

输出

int(123) is: 123
int(123.23) is: 123
int('123') is: 123

示例 2:int() 如何用于十进制、八进制和十六进制?


# binary 0b or 0B
print("For 1010, int is:", int('1010', 2))
print("For 0b1010, int is:", int('0b1010', 2))

# octal 0o or 0O
print("For 12, int is:", int('12', 8))
print("For 0o12, int is:", int('0o12', 8))

# hexadecimal
print("For A, int is:", int('A', 16))
print("For 0xA, int is:", int('0xA', 16))
 

输出

For 1010, int is: 10
For 0b1010, int is: 10
For 12, int is: 10
For 0o12, int is: 10
For A, int is: 10
For 0xA, int is: 10

示例 3:自定义对象的 int()


class Person:
    age = 23

    def __index__(self):
        return self.age
    
    def __int__(self):
        return self.age
 pers
print('int(person) is:', int(person))
 

输出

int(person) is: 23

注意:在内部,int() 方法调用对象的 __int__() 方法。这两个方法应返回相同的值。情况是,旧版本的 Python 使用 __int__(),而新版本使用 __index__() 方法。