网站首页 > 技术文章 正文
26: 编码/解码为十六进制不再可用
Python 2.x Version ≤ 2.7
"1deadbeef3".decode('hex')
# Out: '\x1d\xea\xdb\xee\xf3'
'\x1d\xea\xdb\xee\xf3'.encode('hex')
# Out: 1deadbeef3
Python 3.x Version ≥ 3.0
"1deadbeef3".decode('hex')
# Traceback (most recent call last):
# File "", line 1, in
# AttributeError: 'str' object has no attribute 'decode'
b"1deadbeef3".decode('hex')
# Traceback (most recent call last):
# File "", line 1, in
# LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
'\x1d\xea\xdb\xee\xf3'.encode('hex')
# Traceback (most recent call last):
# File "", line 1, in
# LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
b'\x1d\xea\xdb\xee\xf3'.encode('hex')
# Traceback (most recent call last):
# File "", line 1, in
# AttributeError: 'bytes' object has no attribute 'encode'
然而,正如错误消息所建议的那样,你可以使用codecs模块来实现相同的结果:
import codecs
codecs.decode('1deadbeef4', 'hex')
# Out: b'\x1d\xea\xdb\xee\xf4'
codecs.encode(b'\x1d\xea\xdb\xee\xf4', 'hex')
# Out: b'1deadbeef4'
注意,codecs.encode返回一个字节对象。要获得字符串对象,只需解码为ASCII:
codecs.encode(b'\x1d\xea\xdb\xee\xff', 'hex').decode('ascii')
# Out: '1deadbeeff'
27: 字典方法更改
在Python 3中,许多字典方法的行为与Python 2不同,许多方法也被移除了:has_key、iter*和view*。作为d.has_key(key)的替代,现在必须使用key in d。
在Python 2中,字典方法keys、values和items返回列表。在Python 3中,它们返回视图对象;视图对象不是迭代器,它们与迭代器有两点不同,即:
- 它们有大小(可以使用len函数)
- 它们可以多次迭代
此外,与迭代器一样,字典中的更改会反映在视图对象中。
Python 2.7从Python 3中回退了这些方法;它们分别可用作viewkeys、viewvalues和viewitems。要将Python 2代码转换为Python 3代码,相应的形式是:
- Python 2中的d.keys()、d.values()和d.items()应更改为list(d.keys())、list(d.values())和list(d.items())
- Python 2中的d.iterkeys()、d.itervalues()和d.iteritems()应更改为iter(d)、iter(d.values())和iter(d.items())
- 最后,Python 2.7中的方法调用d.viewkeys()、d.viewvalues()和d.viewitems()可以替换为d.keys()、d.values()和d.items()
将Python 2代码转换为Python 3代码时,有时会比较棘手,尤其是在迭代字典的键、值或项时进行修改。考虑以下代码:
d = {'a': 0, 'b': 1, 'c': 2, '!': 3}
for key in d.keys():
if key.isalpha():
del d[key]
代码看起来像是在Python 3中也会类似地工作,但在这里,keys方法返回的是视图对象,而不是列表,如果在迭代过程中字典大小发生变化,Python 3代码将因RuntimeError而崩溃:在迭代过程中字典大小发生了变化。解决方案当然是正确地写成for key in list(d)。
同样,视图对象的行为与迭代器不同:不能在它们上使用next(),并且不能恢复迭代;相反,它会重新开始;如果Python 2代码将d.iterkeys()、d.itervalues()或d.iteritems()的返回值传递给一个期望迭代器而不是可迭代对象的方法,那么在Python 3中应该是iter(d)、iter(d.values())或iter(d.items())。
28: 类布尔值
Python 2.x Version ≤ 2.7
在Python 2中,如果你想自己定义类的布尔值,你需要在你的类中实现__nonzero__方法。默认值为True。
class MyClass:
def __nonzero__(self):
return False
my_instance = MyClass()
print bool(MyClass) # True
print bool(my_instance) # False
Python 3.x Version ≥ 3.0
在Python 3中,使用__bool__而不是__nonzero__。
class MyClass:
def __bool__(self):
return False
my_instance = MyClass()
print(bool(MyClass)) # True
print(bool(my_instance)) # False
29: Python 2中hasattr函数的错误
在Python 2中,当属性引发错误时,hasattr会忽略该属性,返回False。
class A(object):
@property
def get(self):
raise IOError
class B(object):
@property
def get(self):
return 'get in b'
a = A()
b = B()
print 'a hasattr get: ', hasattr(a, 'get')
# output False in Python 2 (fixed, True in Python 3)
print 'b hasattr get', hasattr(b, 'get')
# output True in Python 2 and Python 3
此错误已在Python 3中修复。因此,如果你使用的是Python 2,可以使用以下代码:
try:
a.get
except AttributeError:
print("no get property!")
或者使用getattr代替:
p = getattr(a, "get", None)
if p is not None:
print(p)
else:
print("no get property!")
猜你喜欢
- 2025-03-26 少儿python编程:找出100以内能被3整除的数
- 2025-03-26 python3从零学习-5.2.1、日历相关模块calendar
- 2025-03-26 Python实现3×3矩阵主对角线元素求和
- 2025-03-26 Python3+requests+unittest接口自动化测试实战
- 2025-03-26 深入理解Python3密码学:详解PyCrypto库加密、解密与数字签名
- 2025-03-26 只用3行Python代码,获取星期几?(python输入星期几的第一个字母判断星期几)
- 2025-03-26 Python3.11版本使用thriftpy2的问题
- 2025-03-26 在Python中有四种方法可以交换两个变量的值,你用过几种?
- 2025-03-26 《Python3官方手册中文版》高清PDF免费下载!内容简直如开挂
- 2025-03-26 Python实现轻量级数据库引擎——用200行代码复刻SQLite3核心功能
- 265℃Python短文,Python中的嵌套条件语句(六)
- 264℃python笔记:for循环嵌套。end=""的作用,图形打印
- 263℃PythonNet:实现Python与.Net代码相互调用!
- 257℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 257℃Python实现字符串小写转大写并写入文件
- 117℃原来2025是完美的平方年,一起探索六种平方的算吧
- 97℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 90℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
-
- 金母鸡量化教学场:pandas—数据挖掘的Python库
- 分享一个用于商业决策数据挖掘的python案例
- Python图像识别实战(二):批量图像读取和像素转换(附源码)
- 从小白到大神,这10个超实用的 Python 编程技巧不可少
- 太震撼!527页战略级Python机器学习实战,实用度碾压群书!附PDF
- 一篇文章带你解析Python进程(一篇文章带你解析python进程怎么写)
- 大数据分析师如何进行数据挖掘?大数据分析师丨 2025 年报考攻略
- UG编程第34节:浅谈机床坐标系(ug编程机床坐标系细节)
- 想入门Python?先狠下心来死磕这7个方向
- Python大屏看板最全教程之Pyecharts图表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)