Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #197039

Re: super().__init__() and bytes

From Roel Schroeven <roel@roelschroeven.net>
Newsgroups comp.lang.python
Subject Re: super().__init__() and bytes
Date 2024-12-03 15:24 +0100
Message-ID <mailman.6.1733235899.2965.python-list@python.org> (permalink)
References <3cc6272f-b151-474a-a83c-7f3339734bf5@roelschroeven.net> <ce4e0a1b-229a-48ad-b256-5835e0e509cc@roelschroeven.net> <VI1PR05MB106809E93AA17A3D46E380DFEB4362@VI1PR05MB10680.eurprd05.prod.outlook.com> <c5901834-52b0-4238-bda1-6b74220be68d@roelschroeven.net>

Show all headers | View raw


Op 3/12/2024 om 13:55 schreef Anders Munch via Python-list:
> Roel Schroeven <roel@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

Back to comp.lang.python | Previous | NextNext in thread | Find similar


Thread

Re: super().__init__() and bytes Roel Schroeven <roel@roelschroeven.net> - 2024-12-03 15:24 +0100
  Re: super().__init__() and bytes Greg Ewing <greg.ewing@canterbury.ac.nz> - 2024-12-04 12:14 +1300
    Re: super().__init__() and bytes Roel Schroeven <roel@roelschroeven.net> - 2024-12-04 12:38 +0100

csiph-web