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'
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短