python - 使用附加属性扩展类时出现类型错误

标签 python python-3.x inheritance

我想扩展标准 python bytes具有一些附加属性的类,以便我可以像任何正常的那样处理它们 bytes objext(例如将它们放入列表中并对它们进行排序)。

因此我创建了自己的类,它继承自 bytes并重写构造函数以获取其他属性,在调用父类 ( bytes ) 构造函数之前设置它们。

class inheritest(bytes):
    def __init__(self, bs: bytes, x: int = 0):
        print("child class init")
        self.x = x
        super().__init__(bs)


print(inheritest(b'foobar', 3))

此方法不起作用:我收到有关传递到 bytes 的参数签名错误的类型错误构造函数,尽管我只在第 5 行使用 bytes 类型的单个参数调用它,应该没问题。
更重要的是,请注意 print 语句永远不会执行,因此 inheritest 的构造函数类永远不会被执行,但参数类型签名检查(引发 TypesError)似乎会提前发生。

Traceback (most recent call last):
  File "inheritest.py", line 8, in <module>
    print(inheritest(b'foobar', 3))
TypeError: bytes() argument 2 must be str, not int

那么我在继承和属性扩展方面做错了什么?

最佳答案

您需要重写__new__才能从字节继承:

class MyBytes(bytes):
    def __new__(cls, *args, **kwargs):
        self = super().__new__(cls, *args, *kwargs)
        return self

现在按照您的意愿进行扩展,我建议这样做:

class MyBytes(bytes):
    def __new__(cls, source, x):
        self = super().__new__(cls, source)
        self.x = x
        return self

    def __str__(self):
        return f"<{repr(self)}, {self.x}>"


b = MyBytes(b"", 3)
print(b)  # <b'', 3>
b = MyBytes(b"345", 5)
print(b)  # <b'345', 5>

注意:

  • 我忽略了bytes接受的其他参数(编码错误)
  • __str__ 仅在您不覆盖 __repr__ 时才有效。
  • MyByte 的实例现在是可变的;根据您的需要,您可以避免更改x(使用属性)并为类设置__slots__属性 - 或者提供考虑 x__hasĥ__ 方法。

这也可以:

class MyBytes(bytes):
    def __new__(cls, source, x):
        self = super().__new__(cls, source)
        return self

    def __init__(self, source, x):
        self.x = x

关于python - 使用附加属性扩展类时出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56850716/

相关文章:

python - 删除 unicode [u']

python - 正则表达式搜索显示不同的结果

使用语音识别将 Python 语音转为文本

python - 在 Python 中按数字阈值排序的有效方法?

c++ - 继承期间 protected 成员的 pimpl

python - 使用 Flask 连接 ParseServer 时出现身份验证错误

python 多处理 - OverflowError ('cannot serialize a bytes object larger than 4GiB' )

python - 尝试使用 aiohttp 构建代理

javascript - 为继承复制原型(prototype)?

c# - 使用 JavaScript/jQuery 从另一个类调用 C# 方法