ZetCode

Python oct 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨了 Python 的 oct 函数,该函数将整数转换为其八进制(以 8 为底)字符串表示形式。 我们将介绍整数转换、自定义对象以及八进制的实际使用示例。

基本定义

oct 函数将整数转换为以 "0o" 为前缀的八进制字符串。 八进制是一种以 8 为基数的数字系统,使用数字 0-7。 每个八进制数字代表三个二进制数字。

主要特征:接受整数(正/负),返回带有 "0o" 前缀的字符串。 对于自定义对象,查找 __index__ 方法。

基本整数转换

这是一个简单的用法,使用不同的整数显示 oct 如何处理正、负和零值。

basic_oct.py
# With positive integers
print(oct(10))     # '0o12'
print(oct(64))     # '0o100'

# With negative integers
print(oct(-10))    # '-0o12'
print(oct(-64))    # '-0o100'

# With zero
print(oct(0))      # '0o0'

此示例显示了带有不同整数值的 oct。 输出始终以 "0o" 前缀开头。 负数在加上前缀前包含一个负号。

第一个转换显示十进制 10 变为八进制 12 (1×8¹ + 2×8⁰)。 第二个显示 64 变为 100 (1×8² + 0×8¹ + 0×8⁰)。

不同的整数表示

oct 适用于不同表示形式的整数(二进制、十六进制、十进制)。 此示例显示了各种输入格式。

representations.py
# Binary literal
print(oct(0b1010))    # '0o12'

# Hexadecimal literal
print(oct(0xA))       # '0o12'

# Decimal literal
print(oct(10))        # '0o12'

# Large number
print(oct(12345678))  # '0o57060516'

该示例演示了 oct 的工作方式与输入格式无关。 二进制 1010、十六进制 A 和十进制 10 都转换为 '0o12'。

大型数字转换显示 oct 可以正确处理大整数,将 12345678 转换为其 8 位八进制等效值。

带有 __index__ 的自定义对象

您可以通过实现 __index__ 特殊方法来使自定义对象与 oct 一起使用。 此示例创建一个自定义类。

custom_oct.py
class MyNumber:
    def __init__(self, value):
        self.value = value
    
    def __index__(self):
        return self.value
    
    def __repr__(self):
        return f"MyNumber({self.value})"

num = MyNumber(42)
print(oct(num))  # '0o52'

MyNumber 类实现了 __index__ 以返回其值。 当我们在实例上调用 oct 时,Python 使用此方法。

此模式对于应支持基本转换操作(如 octhexbin)的自定义数字类型很有用。

错误处理

当与非整数类型一起使用时,oct 函数会引发 TypeError。 此示例显示了正确的错误处理。

errors.py
try:
    print(oct("hello"))
except TypeError as e:
    print(f"Error: {e}")  # 'str' object cannot be interpreted as an integer

class NoIndex:
    pass

try:
    print(oct(NoIndex()))
except TypeError as e:
    print(f"Error: {e}")  # 'NoIndex' object cannot be interpreted as an integer

这些示例演示了 oct 在不支持的类型上的行为。 没有 __index__ 的字符串和对象会引发 TypeError

要使类与 oct 一起使用,请如上一个示例中所示实现 __index__

实际文件权限示例

此示例显示了八进制数字的一个实际用途,用于表示 Unix 文件权限,这是八进制表示法的常见实际应用。

permissions.py
def describe_permission(octal_perm):
    perm = int(octal_perm, 8)
    owner = (perm >> 6) & 0b111
    group = (perm >> 3) & 0b111
    others = perm & 0b111
    
    def perm_str(p):
        return f"{'r' if p & 4 else '-'}{'w' if p & 2 else '-'}{'x' if p & 1 else '-'}"
    
    return f"Owner: {perm_str(owner)}, Group: {perm_str(group)}, Others: {perm_str(others)}"

print(describe_permission('755'))  # Owner: rwx, Group: r-x, Others: r-x
print(describe_permission('644'))  # Owner: rw-, Group: r--, Others: r--

此函数接受八进制权限字符串(如“755”)并将其转换为人类可读的格式。 每个数字代表所有者、组和其他人的权限。

该示例演示了八进制数字如何紧凑地表示每个数字的三个权限位(读取=4,写入=2,执行=1)。 这就是八进制通常用于文件权限的原因。

最佳实践

资料来源

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 到目前为止,我已撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程