super().__init__() and bytes
Anders Munch
ajm at flonidan.dk
Tue Dec 3 07:55:59 EST 2024
Roel Schroeven <roel at roelschroeven.net> wrote:
> As a follow-up, it looks like this behavior is because bytes and int are immutable.
Yes.
> But that doesn't tell me why using super().__init__(<custom arguments>) doesn't work for immutable classes.
bytes.__init__ does work, but it's just an inherited object.__init__, which does nothing, and takes no parameters.
__init__ cannot change the value of the bytes object; the value is set by bytes.__new__ and cannot change after that.
Best not to define an __init__ method at all, just use __new__.
Something like:
class BytesSubclass(bytes):
def __new__(cls, whatever, arguments, you, like):
bytesvalue = compute(whatever, arguments, you, like)
ob = bytes.__new__(cls, bytesvalue)
ob.some_other_att = compute_something_else(whatever, arguments, you, like)
return ob
regards,
Anders
More information about the Python-list
mailing list