內置函數oct()
用於獲取給定整數的八進位值。此方法接受單個參數,並返回前綴為「0o」的轉換後的八進位字元串。
**oct(x)** #where x must be an integer number and can be binary,decimal or hexadecimal format
oct()
參數:
接受單個參數。如果參數類型不是整數,此函數將引發類型錯誤。
參數 | 描述 | 必需/可選 |
---|---|---|
整數 | 可能是二進位、十進位或十六進位 | 需要 |
十月()返回值
如果我們傳遞一個對象作為參數,在這種情況下,該對象必須有__index__()
函數實現才能返回一個整數。
| 投入 | 返回值 |
| 整數 | 八進位字元串 |
Python 中oct()
方法的示例
示例oct()
在 Python 中是如何工作的?
# decimal to octal
print('oct(10) is:', oct(10))
# binary to octal
print('oct(0b101) is:', oct(0b101))
# hexadecimal to octal
print('oct(0XA) is:', oct(0XA))
輸出:
oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12
示例 2:自定義對象的oct()
class Person:
age = 23
def __index__(self):
return self.age
def __int__(self):
return self.age
pers
print('The oct is:', oct(person))
輸出:
The oct is: 0o27
這裡,Person 類實現了__index__()
和__index__()
。那是因為我們可以在 Person 的對象上使用__index__()
。
示例oct()
函數拋出一個錯誤
# Python `oct()` function example
# Calling function
val = oct(10.25)
# Displaying result
print("Octal value of 10.25:",val)
輸出:
TypeError: 'float' object cannot be interpreted as an integer
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/307367.html