python 核心数
Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”.
Python hex()函数用于将整数转换为以“ 0x”为前缀的小写十六进制字符串。
We can also pass an object to hex() function, in that case the object must have __index__()
function defined that returns integer.
我们还可以将一个对象传递给hex()函数,在这种情况下,该对象必须定义返回整数的__index__()
函数。
The input integer argument can be in any base such as binary, octal etc. Python will take care of converting them to hexadecimal format.
输入的整数参数可以是任何基数,例如二进制,八进制等。Python将负责将它们转换为十六进制格式。
Python hex()示例 (Python hex() example)
Let’s look into some simple examples of converting integer to hexadecimal number.
让我们看一些将整数转换为十六进制数的简单示例。
print(hex(255)) # decimal
print(hex(0b111)) # binary
print(hex(0o77)) # octal
print(hex(0XFF)) # hexadecimal
Output:
输出:
0xff
0x7
0x3f
0xff
带有对象的Python hex() (Python hex() with object)
Let’s create a custom class and define __index__() function so that we can use hex() function with it.
让我们创建一个自定义类并定义__index __()函数,以便我们可以对其使用hex()函数。
class Data:
id = 0
def __index__(self):
print('__index__ function called')
return self.id
d = Data()
d.id = 100
print(hex(d))
Output:
输出:
__index__ function called
0x64
Reference: Official Documentation
参考: 官方文档
python 核心数