亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Python內(nèi)置函數(shù)OCT詳解

Original 2017-01-12 14:57:53 330
abstract:本文給大家介紹的是python中的內(nèi)置函數(shù)oct(),其主要作用是將十進(jìn)制數(shù)轉(zhuǎn)換成八進(jìn)制,再變成字符。有需要的小伙伴可以參考下oct ( x ) Convert an integer number to an octal string. The result is&nb

本文給大家介紹的是python中的內(nèi)置函數(shù)oct(),其主要作用是將十進(jìn)制數(shù)轉(zhuǎn)換成八進(jìn)制,再變成字符。有需要的小伙伴可以參考下

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. 函數(shù)功能將一個(gè)整數(shù)轉(zhuǎn)換成8進(jìn)制字符串。如果傳入浮點(diǎn)數(shù)或者字符串均會(huì)報(bào)錯(cuò)。

>>> a = oct(10) 
>>> a
'0o12'
>>> type(a) # 返回結(jié)果類型是字符串
<class 'str'> 
>>> oct(10.0) # 浮點(diǎn)數(shù)不能轉(zhuǎn)換成8進(jìn)制
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') # 字符串不能轉(zhuǎn)換成8進(jìn)制
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
  oct('10')
TypeError: 'str' object cannot be interpreted as an integer

2. 如果傳入?yún)?shù)不是整數(shù),則其必須是一個(gè)定義了__index__并返回整數(shù)函數(shù)的類的實(shí)例對象。

# 未定義__index__函數(shù),不能轉(zhuǎn)換
>>> 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__函數(shù),但是返回值不是int類型,不能轉(zhuǎn)換
>>> 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__函數(shù),而且返回值是int類型,能轉(zhuǎn)換
>>> 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'

更多關(guān)于Python內(nèi)置函數(shù)OCT詳解請關(guān)注PHP中文網(wǎng)(ipnx.cn)其他文章!

Release Notes

Popular Entries