新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:Pythonint()
int()函數(shù)有助于將給定值轉(zhuǎn)換為整數(shù)。結(jié)果整數(shù)值總是以 10 為基數(shù)。如果我們對一個自定義對象使用int(),那么將調(diào)用對象__int__() 函數(shù)。

**int(x=0, base=10)**# Where x can be Number or string
int()參數(shù):
接受 2 個參數(shù),其中第一個參數(shù)“x”的默認值為 0。而第二個參數(shù)‘base’的默認值是 10,它也可以在 0(代碼文字)或 2-36 之間。
| 參數(shù) | 描述 | 必需/可選 |
|---|---|---|
| x | 要轉(zhuǎn)換為整數(shù)對象的數(shù)字或字符串。 | 需要 |
| 基礎 | x 中數(shù)字的基數(shù) | 可選擇的 |
int()返回值
| 投入 | 返回值 | | 整數(shù)對象 | 基數(shù)為 10 | | 沒有參數(shù) | 返回 0 | | 如果給定基數(shù) | 在給定的基數(shù)(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 注意:在內(nèi)部,int()方法調(diào)用對象的__int__()方法。這兩種方法應該返回相同的值。情況是舊版 Python 使用__int__(),而新版 Python 使用__int__()方法。
新聞名稱:創(chuàng)新互聯(lián)Python教程:Pythonint()
文章URL:http://m.fisionsoft.com.cn/article/dpisjcg.html


咨詢
建站咨詢
