python内置函数hex_Python3.6内置函数(30)——hex()

本文介绍了Python的内置函数hex(),用于将十进制整数转换为十六进制字符串,并以'0x'开头。当传入的对象不是整数时,它需要定义返回整数的__index__方法。通过示例展示了如何正确使用和定义__index__方法。
摘要由CSDN通过智能技术生成

本文目录

英文文档

hex()

小结

英文文档

hex(x)

Convert an integer number to a lowercase hexadecimal string prefixed with “0x”.

hex()

1、函数功能将10进制整数转换成16进制整数。

>>> hex(16) '0x10' >>> hex(15) '0xf'

2、如果参数x不是整数,则它必须定义一个返回整数的__index__函数。

>>> # 未定义__index__函数 >>> class Student: def __init__(self,name,age): self.name = name self.age = age >>> s = Student('Airy', 18) >>> hex(s) Traceback (most recent call last): File "", line 1, in hex(s) TypeError: 'Student' object cannot be interpreted as an integer >>> # 定义__index__函数,但是返回字符串 >>> class Student: def __init__(self,name,age): self.name = name self.age = age def __index__(self): return self.name >>> s = Student('Airy', 18) >>> hex(s) Traceback (most recent call last): File "", line 1, in hex(s) TypeError: __index__ returned non-int (type str) >>> >>> # 定义__index__函数,并返回整数 >>> class Student: def __init__(self,name,age): self.name = name self.age = age def __index__(self): return self.age >>> s = Student('Airy', 18) >>> hex(s) '0x12' 小结

希望通过上面的操作能帮助大家。如果你有什么好的意见,建议,或者有不同的看法,我都希望你留言和我们进行交流、讨论。

欢迎关注微信公众号,谢谢大家支持:AiryData。

转载请注明:数据之美 Python3.6内置函数(30)——hex()

喜欢 ( 0) or 分享 (0)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值