As a follow-up, it looks like this behavior is because bytes and int are immutable.
But that doesn't tell me why using super().__init__(<custom arguments>) doesn't work for immutable classes.
Roel Schroeven <roel@roelschroeven.net> wrote:OK.
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__.Thanks, that works perfectly. That's also more important than
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
It's not entirely clear to me though how bytes.__new__ *can* set an
object's value. Isn't __new__ also a regular function?
On 4/12/24 3:24 am, Roel Schroeven wrote:Aha, yes, that's what I already suspected, but I wasn't sure. Thanks for confirming that.
It's not entirely clear to me though how bytes.__new__ *can* set an
object's value. Isn't __new__ also a regular function?
Yes, but the __new__ methods of the builtin immutable objects (int,
str, bytes, etc.) are implemented in C, and so are able to do things
that Python methods cannot.
Sysop: | DaiTengu |
---|---|
Location: | Appleton, WI |
Users: | 1,064 |
Nodes: | 10 (0 / 10) |
Uptime: | 149:58:21 |
Calls: | 13,691 |
Calls today: | 1 |
Files: | 186,936 |
D/L today: |
438 files (115M bytes) |
Messages: | 2,410,967 |