TypeError:字符串参数在3.4中没有编码,但在3.6中没有编码

2024-09-26 04:59:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个类,用base64编码的字符串表示LZMA压缩数据:

from base64 import b64decode
from lzma import LZMADecompressor


class B64LZMA(str):
    """A string of base64 encoded, LZMA compressed data."""

    def __bytes__(self):
        """Returns the decompressed data."""
        return LZMADecompressor().decompress(b64decode(self.encode()))

    def __str__(self):
        """Returns the string decoded from __bytes__."""
        return bytes(self).decode()


TEST_STR = B64LZMA('/Td6WFoAAATm1rRGAgAhARYAAAB0L+WjAQALSGVsbG8gd29ybGQuAGt+oFiSvoAYAAEkDKYY2NgftvN9AQAAAAAEWVo=')

if __name__ == '__main__':
    print(TEST_STR)

虽然这在ArchLinux上的python3.6中运行得很好,但是在Debian 8上的python3.4上我得到了以下错误:

^{pr2}$

为什么Python3.4和Python3.6在行为上会有这种差异?如何让上面的类也在Python3.4中工作?在

更新

要验证的脚本:

#! /usr/bin/env python3

from base64 import b64decode
from lzma import LZMADecompressor
from sys import version


class B64LZMA(str):
    """A string of base64 encoded, LZMA compressed data."""

    def __bytes__(self):
        """Returns the decompressed data."""
        return LZMADecompressor().decompress(b64decode(self.encode()))

    def __str__(self):
        """Returns the string decoded from __bytes__."""
        return bytes(self).decode()


TEST_STR = B64LZMA('/Td6WFoAAATm1rRGAgAhARYAAAB0L+WjAQALSGVsbG8gd29ybGQuAGt+oFiSvoAYAAEkDKYY2NgftvN9AQAAAAAEWVo=')

if __name__ == '__main__':
    print(version)
    print(TEST_STR)

SHA-256金额:64513A7508B20DDA5CC26C37FA4DC8F5163699937569833BB0957C10EA887AE00

在Debian 8上使用python 3.4输出:

$ ./test.py 
3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1]
Traceback (most recent call last):
  File "./test.py", line 24, in <module>
    print(TEST_STR)
  File "./test.py", line 17, in __str__
    return bytes(self).decode()
TypeError: string argument without an encoding

在ArchLinux上使用python 3.6输出:

$ ./test.py 
3.6.4 (default, Dec 23 2017, 19:07:07) 
[GCC 7.2.1 20171128]
Hello world.

Tags: fromtestimportselfdatastringreturnbytes
1条回答
网友
1楼 · 发布于 2024-09-26 04:59:16

好的,在python3.4中,bytes()从string继承的对象上,__bytes__似乎无法识别。在

通过显式调用__str__()更改__str__()方法修复了此问题:

def __str__(self):
    """Returns the string decoded from __bytes__."""
    return self.__bytes__().decode()

相关问题 更多 >