Re: super().__init__() and bytes

Liste des GroupesRevenir à cl python 
Sujet : Re: super().__init__() and bytes
De : roel (at) *nospam* roelschroeven.net (Roel Schroeven)
Groupes : comp.lang.python
Date : 03. Dec 2024, 15:24:55
Autres entêtes
Message-ID : <mailman.6.1733235899.2965.python-list@python.org>
References : 1 2 3 4
User-Agent : Mozilla Thunderbird
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

Date Sujet#  Auteur
3 Dec 24 * Re: super().__init__() and bytes3Roel Schroeven
4 Dec 24 `* Re: super().__init__() and bytes2Greg Ewing
4 Dec 24  `- Re: super().__init__() and bytes1Roel Schroeven

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal