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.
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 '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. 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 "
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('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'
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)!