47. python oct()

发布时间:2023-12-08

python oct()

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

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

oct()参数:

接受单个参数。如果参数类型不是整数,此函数将引发类型错误。

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

oct()返回值

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

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

Python 中oct()方法的示例

示例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
person = Person()
print('The oct is:', oct(person))

输出:

The oct is: 0o27

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

示例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