Python内置函数OCT详解
英文文档:
oct(x) Convertanintegernumbertoanoctalstring.TheresultisavalidPythonexpression.IfxisnotaPythonobject,ithastodefineanmethodthatreturnsaninteger.
说明:
1.函数功能将一个整数转换成8进制字符串。如果传入浮点数或者字符串均会报错。
>>>a=oct(10)
>>>a
'0o12'
>>>type(a)#返回结果类型是字符串
<class'str'>
>>>oct(10.0)#浮点数不能转换成8进制
Traceback(mostrecentcalllast):
File"<pyshell#3>",line1,in<module>
oct(10.0)
TypeError:'float'objectcannotbeinterpretedasaninteger
>>>oct('10')#字符串不能转换成8进制
Traceback(mostrecentcalllast):
File"<pyshell#4>",line1,in<module>
oct('10')
TypeError:'str'objectcannotbeinterpretedasaninteger
2.如果传入参数不是整数,则其必须是一个定义了__index__并返回整数函数的类的实例对象。
#未定义__index__函数,不能转换
>>>classStudent:
def__init__(self,name,age):
self.name=name
self.age=age
>>>a=Student('Kim',10)
>>>oct(a)
Traceback(mostrecentcalllast):
File"<pyshell#12>",line1,in<module>
oct(a)
TypeError:'Student'objectcannotbeinterpretedasaninteger
#定义了__index__函数,但是返回值不是int类型,不能转换
>>>classStudent:
def__init__(self,name,age):
self.name=name
self.age=age
def__index__(self):
returnself.name
>>>a=Student('Kim',10)
>>>oct(a)
Traceback(mostrecentcalllast):
File"<pyshell#18>",line1,in<module>
oct(a)
TypeError:__index__returnednon-int(typestr)
#定义了__index__函数,而且返回值是int类型,能转换
>>>classStudent:
def__init__(self,name,age):
self.name=name
self.age=age
def__index__(self):
returnself.age
>>>a=Student('Kim',10)
>>>oct(a)
'0o12'
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志