Tutorial Study Image

Python oct()

内置函数 oct() 用于获取给定整数的八进制值。此方法接受一个参数,并返回以“0o”为前缀的转换后的八进制字符串。


oct(x) #where x must be an integer number and can be binary,decimal or hexadecimal format
 

oct() 参数

接受一个参数。如果参数类型不是整数,此函数将引发 TypeError。

参数 描述 必需/可选
整数 可以是二进制、十进制或十六进制 必需

oct() 返回值

如果我们将对象作为参数传递,在这种情况下,对象必须具有 __index__() 函数实现以返回整数。

输入 返回值
整数 八进制字符串

Python 中 oct() 方法的示例

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


# 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
 pers
print('The oct is:', oct(person))
 

输出

The oct is: 0o27

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

示例 3:oct() 函数引发错误


# Python oct() function example  
# Calling function  
val = oct(10.25)  
# Displaying result  
print("Octal value of 10.25:",val)  
 

输出

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