Python內置函數(46)——oct


英文文檔:

oct (x)
Convert an integer number to an octal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

 

說明:
  1. 函數功能將一個整數轉換成8進制字符串。如果傳入浮點數或者字符串均會報錯。
>>> a = oct(10)

>>> a
'0o12'
>>> type(a) # 返回結果類型是字符串
<class 'str'>

>>> oct(10.0) # 浮點數不能轉換成8進制
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    oct(10.0)
TypeError: 'float' object cannot be interpreted as an integer

>>> oct('10') # 字符串不能轉換成8進制
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    oct('10')
TypeError: 'str' object cannot be interpreted as an integer

  2. 如果傳入參數不是整數,則其必須是一個定義了__index__並返回整數函數的類的實例對象。

# 未定義__index__函數,不能轉換
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age

        
>>> a = Student('Kim',10)
>>> oct(a)
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    oct(a)
TypeError: 'Student' object cannot be interpreted as an integer

# 定義了__index__函數,但是返回值不是int類型,不能轉換
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __index__(self):
        return self.name

>>> a = Student('Kim',10)
>>> oct(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    oct(a)
TypeError: __index__ returned non-int (type str)

# 定義了__index__函數,而且返回值是int類型,能轉換
>>> class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def __index__(self):
        return self.age

>>> a = Student('Kim',10)
>>> oct(a)
'0o12'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM