【发布时间】:2019-11-12 23:57:39
【问题描述】:
我想用一些额外的属性扩展标准 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
那么我在继承和属性扩展方面做错了什么?
【问题讨论】:
标签: python python-3.x inheritance