Python的程序结构[2] -> 类/Class[5] -> 内建类 bytes 和 bytearray

内建类 bytes 和 bytearray / Built-in Type bytes and bytearray


关于内建类

Python的内建类 bytes 主要有以下几点:

class bytes([source[, encoding[, errors]]])

    Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are interpreted as for bytearray().

1. 返回值为一个新的不可修改字节数组,每个数字元素都必须在0 - 255范围内,是bytearray函数的具有相同的行为,差别仅仅是返回的字节数组不可修改;

2. 当3个参数都不传的时候,返回长度为0的字节数组;

3. 当source参数为字符串时,encoding参数也必须提供,函数将字符串使用str.encode方法转换成字节数组;

4. 当source参数为整数时,返回这个整数所指定长度的空字节数组;

5. 当source参数为实现了buffer接口的object对象时,那么将使用只读方式将字节读取到字节数组后返回;

6. 当source参数是一个可迭代对象,那么这个迭代对象的元素都必须符合0 <= x < 256,以便可以初始化到数组里;

7. 返回数组不可修改。

>>> bytes(1)  
b'\x00'  
>>> bytes([1, 2, 3])  
b'\x01\x02\x03'  

对于 bytes 与 bytearray 的最大区别在于 bytes 生成的对象不可修改,

 1 s = '@MOVE\r\n'
 2 
 3 m = bytearray(s, encoding='ascii')
 4 x = bytes(s, encoding='ascii')
 5 
 6 m[0] = 65
 7 try:
 8     x[0] = 65
 9 except:
10     pass
11 
12 print(m, x, sep='\n')

通过输出可以看到,m 被修改而 x 未被修改

bytearray(b'AMOVE\r\n')  
b'@MOVE\r\n'  

 

相关阅读


1. 关于内建类

 

参考链接

http://www.cnblogs.com/sesshoumaru/p/5980090.html

 

转载于:https://www.cnblogs.com/stacklike/p/8099087.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值