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 升班祝福语简短10字
12 生日祝福语 简短独特潮
13 紫玫瑰生日祝福语简短
14 新单位成立祝福语简短
15 微信立冬祝福语简短
17 同学毕业祝福语有趣简短
18 旅游祝福语简短老师发言