zoukankan      html  css  js  c++  java
  • 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'x01x02x03'  

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

     1 s = '@MOVE
    '
     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='
    ')

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

    bytearray(b'AMOVE
    ')  
    b'@MOVE
    '  

    相关阅读


    1. 关于内建类

    参考链接


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

  • 相关阅读:
    HDU 5818 Joint Stacks
    HDU 5816 Hearthstone
    HDU 5812 Distance
    HDU 5807 Keep In Touch
    HDU 5798 Stabilization
    HDU 5543 Pick The Sticks
    Light OJ 1393 Crazy Calendar (尼姆博弈)
    NEFU 2016省赛演练一 I题 (模拟题)
    NEFU 2016省赛演练一 F题 (高精度加法)
    NEFU 2016省赛演练一 B题(递推)
  • 原文地址:https://www.cnblogs.com/stacklike/p/8099087.html
Copyright © 2011-2022 走看看