Op 3/12/2024 om 13:55 schreef Anders Munch via Python-list:
Roel Schroeven <r...@roelschroeven.net> wrote:
> As a follow-up, it looks like this behavior is because bytes and int are
immutable.
Yes.
OK.
> 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.
I see now why __init__, being a regular method, can't change an object's
value (or attributes in general) if that object is immutable. I'm not
sure why I didn't think of that before.
It's not entirely clear to me though how bytes.__new__ *can* set an
object's value. Isn't __new__ also a regular function? Are these
immutable classes special cases in the language that can't be recreated
in the same way with user-defined classes? Not that that's something I
want to do, and it's also not terribly important to me, but I'm trying
to better understand what's going on.
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
Thanks, that works perfectly. That's also more important than
understanding all the nitty-gritty details (I feel a basic understanding
is important, but not necessarily always all the low-level details).
--
"There is no cause so noble that it will not attract fuggheads."
-- Larry Niven
--
https://mail.python.org/mailman/listinfo/python-list