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 生日开业蛋糕祝福语简短