oct() 函數接受一個整數並返回其八進製表示。
用法:
oct(x)
參數:
oct()
函數接受一個參數x.
這個參數可以是:
- 整數(二進製、十進製或十六進製)
- 如果不是整數,則應實現
__index__()
以返回整數
返回:
oct()
函數從給定的整數返回一個八進製字符串。
示例 1: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
person = Person()
print('The oct is:', oct(person))
輸出
The oct is: 0o27
在這裏,Person
類實現了 __index__()
和 __int__()
。這就是為什麽我們可以在 Person
的對象上使用 oct()
的原因。
注意:為了兼容性,建議實現__int__()
和__index__()
具有相同的輸出。
相關用法
- Python oct()用法及代碼示例
- Python os.path.normcase()用法及代碼示例
- Python os.read()用法及代碼示例
- Python os.DirEntry.inode()用法及代碼示例
- Python os.closerange()用法及代碼示例
- Python os.set_blocking()用法及代碼示例
- Python os.pathconf()用法及代碼示例
- Python os.chflags()用法及代碼示例
- Python operator.truth()用法及代碼示例
- Python operator.le()用法及代碼示例
- Python os.WCOREDUMP()用法及代碼示例
- Python os.fork()用法及代碼示例
- Python os.ctermid()用法及代碼示例
- Python os.mkfifo()用法及代碼示例
- Python os.tcsetpgrp()用法及代碼示例
- Python os.path.commonpath()用法及代碼示例
- Python os.mkdir()用法及代碼示例
- Python os.close()用法及代碼示例
- Python os.chroot()用法及代碼示例
- Python os.path.expanduser()用法及代碼示例
注:本文由純淨天空篩選整理自 Python oct()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。