Python内置函数OCT详解

yipeiwu_com5年前Python基础

英文文档:

复制代码 代码如下:
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. 函数功能将一个整数转换成8进制字符串。如果传入浮点数或者字符串均会报错。

>>> a = oct(10)

>>> a
'0o12'
>>> type(a) # 返回结果类型是字符串
<class 'str'>

>>> oct(10.0) # 浮点数不能转换成8进制
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') # 字符串不能转换成8进制
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
  oct('10')
TypeError: 'str' object cannot be interpreted as an integer

2. 如果传入参数不是整数,则其必须是一个定义了__index__并返回整数函数的类的实例对象。

# 未定义__index__函数,不能转换
>>> 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__函数,但是返回值不是int类型,不能转换
>>> 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__函数,而且返回值是int类型,能转换
>>> 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'

相关文章

使用pyhon绘图比较两个手机屏幕大小(实例代码)

使用pyhon绘图比较两个手机屏幕大小(实例代码)

背景:准备给长辈买个手机,有关手机大小,网购平台基本只有手机尺寸和分辨率的文本数据,因而对手机屏幕大小没有直观感受,虽然网上有比较手机大小的网站(百度搜索),但是只有知名的手机才有数据,...

Python中栈、队列与优先级队列的实现方法

前言 栈、队列和优先级队列都是非常基础的数据结构。Python作为一种“编码高效”的语言,对这些基础的数据结构都有比较好的实现。在业务需求开发过程中,不应该重复造轮子,今天就来看看些数据...

Python open读写文件实现脚本

1.open使用open打开文件后一定要记得调用文件对象的close()方法。比如可以用try/finally语句来确保最后能关闭文件。file_object = op...

Python中的取模运算方法

Python中的取模运算方法

所谓取模运算,就是计算两个数相除之后的余数,符号是%。如a % b就是计算a除以b的余数。用数学语言来描述,就是如果存在整数n和m,其中0 <= m < b,使得a = n...

python requests更换代理适用于IP频率限制的方法

python requests更换代理适用于IP频率限制的方法

有些网址具有IP限制,比如同一个IP一天只能点赞一次。 解决方法就是更换代理IP。 从哪里获得成千上万的IP呢? 百度“http代理” 可获得一大堆网站。 比如某代理网站,1天...