我想扩展标准 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/