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://www.506064.com/zh-hant/n/275808.html