跳到主要内容

Python oct() 函数

oct() 的语法是:

oct(x)

oct() 参数

oct() 函数接受单个参数 x

这个参数可以是:

  • 一个整数(二进制、十进制或十六进制)
  • 如果不是整数,它应该实现 __index__() 方法返回一个整数

从 oct() 返回值

oct() 函数将给定的整数转换为八进制字符串并返回。

示例 1:oct() 在 Python 中如何工作?

# 十进制转八进制
print('oct(10) is:', oct(10))

# 二进制转八进制
print('oct(0b101) is:', oct(0b101))

# 十六进制转八进制
print('oct(0XA) is:', oct(0XA))

输出

oct(10) is: 0o12
oct(0b101) is: 0o5
oct(0XA) is: 0o12

示例 2:自定义对象的 oct()

class Person:
age = 23

def __index__(self):
return self.age

def __int__(self):
return self.age

person = Person()
print('The oct is:', oct(person))

输出

The oct is: 0o27

在这里,Person 类实现了 __index__()__int__()。这就是为什么我们可以在 Person 的对象上使用 oct()

注意: 为了兼容性,建议 __int__()__index__() 有相同的输出。