Python內建函數OCT詳解_python

來源:互聯網
上載者:User

英文文檔:

複製代碼 代碼如下:
oct ( x )
Convert an integer number to an octal string. The result is a valid Python expression. If x is not a Pythonobject, it has to define anmethod 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'

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.