Python oct()

oct() 的语法是

oct(x)

oct() 参数

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

此参数可以是

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

oct() 的返回值

oct() 函数从给定的整数返回一个八进制字符串


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

# decimal to octal
print('oct(10) is:', oct(10))

# binary to octal
print('oct(0b101) is:', oct(0b101))

# hexadecimal to octal
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__()


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战