Home > Backend Development > Python Tutorial > Detailed explanation of Python built-in function OCT

Detailed explanation of Python built-in function OCT

黄舟
Release: 2016-12-15 09:24:30
Original
1281 people have browsed it

English document:

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.
Copy after login

Instructions:

1. The function converts an integer into an octal string. If you pass in a floating point number or a string, an error will be reported.

>>> a = oct(10)
  
>>> a
'0o12'
>>> type(a) # 返回结果类型是字符串
<class &#39;str&#39;>
  
>>> oct(10.0) # 浮点数不能转换成8进制
Traceback (most recent call last):
 File "<pyshell#3>", line 1, in <module>
  oct(10.0)
TypeError: &#39;float&#39; object cannot be interpreted as an integer
  
>>> oct(&#39;10&#39;) # 字符串不能转换成8进制
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
  oct(&#39;10&#39;)
TypeError: &#39;str&#39; object cannot be interpreted as an integer
Copy after login

2. If the incoming parameter is not an integer, it must be an instance object of a class that defines __index__ and returns an integer function.

# The __index__ function is not defined and cannot be converted

>>> 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 "", line 1, in

oct(a)

TypeError: 'Student' object cannot be interpreted as an integer

# The __index__ function is defined, but the return value is not int Type, cannot be converted

>>> class Student:
  def __init__(self,name,age):
    self.name = name
    self.age = age
  def __index__(self):
    return self.name
  
>>> a = Student(&#39;Kim&#39;,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(&#39;Kim&#39;,10)
>>> oct(a)
&#39;0o12&#39;
Copy after login

The above is the detailed explanation of Python’s built-in function OCT. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template