Python 的 oct(~)
方法將整數轉換為前綴為 "0o"
的八進製字符串。如果提供的輸入不是整數,則必須實現 __index__()
方法來返回整數。
參數
1. x
| integer
要轉換為八進製字符串的整數。
返回值
以 "0o"
為前綴的整數轉換後的八進製字符串。
例子
基本用法
要返回 87
的八進製字符串:
oct(87)
'0o127'
請注意,"0o"
僅表示它是八進製字符串。
__index__()方法
要將 oct(~)
方法與實現 __index__()
方法的輸入結合使用:
class score:
james = 20
sally = 40
tom = 30
def __index__(self):
return self.james + self.sally + self.tom
oct(score())
'0o132'
我們提供 score
類的實例作為 oct(~)
方法的輸入。盡管實例本身不是整數,但由於它返回一個整數(james + sally + tom
的和),在本例中為 90
,因此 oct(~)
返回 90
的八進製字符串。
TypeError
如果我們提供整數以外的輸入:
oct('Hi')
TypeError: 'str' object cannot be interpreted as an integer
相關用法
- Python oct()用法及代碼示例
- Python oct用法及代碼示例
- Python NumPy ones方法用法及代碼示例
- 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 open()用法及代碼示例
- Python operator.truth()用法及代碼示例
- Python os.WCOREDUMP()用法及代碼示例
- Python os.fork()用法及代碼示例
- Python os.ctermid()用法及代碼示例
- Python os.mkfifo()用法及代碼示例
- Python os.tcsetpgrp()用法及代碼示例
- Python os.path.commonpath()用法及代碼示例
- Python os.path.splitdrive用法及代碼示例
- Python os.mkdir()用法及代碼示例
- Python os.close()用法及代碼示例
- Python os.chroot()用法及代碼示例
- Python os.ttyname()用法及代碼示例
- Python os.path.splitext用法及代碼示例
- Python os.setregid()用法及代碼示例
注:本文由純淨天空篩選整理自Arthur Yanagisawa大神的英文原創作品 Python | oct method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。