I want to extend the standard python bytes
class with some additional attributes, so that I can handle them like any normal bytes
objext (e.g. putting them into a list and sort them).
Thus I created my own class that inherits from bytes
and overrode the constructor to take additional attributes, setting them before invoking the parent class (bytes
) constructor.
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))
This approach does not work: I get a type error about a wrong argument signature being passed to the bytes
constructor, although I only invoke it in line 5 with a single argument of the type bytes
, which should be fine.
Even more, note that the print statement is never executed, so the constructor of the inheritest
class is never executed but the argument type signature check, raising the TypesError, seems to happen beforehand.
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
So what am I doing wrong about inheritance and attribute extension?