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 要转换为整数对象的数字或字符串。 需要
基础 x 中数字的基数 可选择的

int()返回值

| 投入 | 返回值 | | 整数对象 | 基数为 10 | | 没有参数 | 返回 0 | | 如果给定基数 | 在给定的基数(0,2,8,10,16)下 |

Python 中int()方法的示例

示例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 

示例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__(),而新版 Python 使用__int__()方法。

本文链接:https://my.lmcjl.com/post/6315.html

展开阅读全文

4 评论

留下您的评论.