当前位置: 首页 > 工具软件 > oct > 使用案例 >

[转载] python oct_Python oct()

袁秦迟
2023-12-01

参考链接: Python oct()

python oct

 

  

  

 

 Python oct() function is used to convert an integer into octal string prefixed with “0o”.

  Python oct()函数用于将整数转换为以“ 0o”为前缀的八进制字符串。  

  Python oct() (Python oct()) 

 Python oct() function syntax is:

  Python oct()函数语法为:  

 

  

 oct(x)

 The output of oct() function is a string. We can pass an object as an argument too, in that case, the object must have __index__() function implementation that returns integer.

  oct()函数的输出为string 。 我们也可以将对象作为参数传递,在这种情况下,该对象必须具有返回整数的__index__()函数实现。  

 Let’s look at some simple examples of oct() function.

  让我们看一下oct()函数的一些简单示例。  

 

  

  

 

 print(oct(10))

 

print(oct(0xF))

 

print(oct(0b1111))

 

print(type(oct(10)))

 Output:

  输出:  

 0o12

0o17

0o17

<class 'str'>

  带有对象的Python oct() (Python oct() with object) 

 Let’s look at another example where we will use oct() function with a custom object as an argument. We will implement __index__() function in this object.

  让我们看另一个示例,在该示例中我们将使用带有自定义对象作为参数的oct()函数。 我们将在此对象中实现__index __()函数。  

 

  

  

 

 class Data:

    id = 0

 

    def __init__(self, i):

        self.id = i

 

    def __index__(self):

        return self.id

 

 

d = Data(20)

 

print(oct(d))

 Output: 0o24

  输出: 0o24  

 

  GitHub Repository.

  GitHub存储库中检出完整的python脚本和更多Python示例。 

 

 Reference: Official Documentation

  参考: 官方文档  

 

  翻译自: https://www.journaldev.com/22991/python-oct

 

 python oct

 类似资料: