Python built in function OCT

  • 2020-05-17 05:45:00
  • OfStack

English documents:

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.

Description:

1. The function converts an integer into an 8-character string. An error is reported if a floating point number or string is passed in.


>>> a = oct(10)

>>> a
'0o12'
>>> type(a) #  The return result type is a string 
<class 'str'>

>>> oct(10.0) #  Floating point Numbers cannot be converted to 8 Into the system 
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') #  String cannot be converted to 8 Into the system 
Traceback (most recent call last):
 File "<pyshell#4>", line 1, in <module>
  oct('10')
TypeError: 'str' object cannot be interpreted as an integer

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


#  undefined __index__ Function, 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 "<pyshell#12>", line 1, in <module>
  oct(a)
TypeError: 'Student' object cannot be interpreted as an integer

#  Defines the __index__ Function, 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('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)

#  Defines the __index__ Function, and the return value is int Type, can be converted 
>>> 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'


Related articles: