RE: super().__init__() and bytes

Liste des GroupesRevenir à cl python 
Sujet : RE: super().__init__() and bytes
De : ajm (at) *nospam* flonidan.dk (Anders Munch)
Groupes : comp.lang.python
Date : 03. Dec 2024, 13:55:59
Autres entêtes
Message-ID : <mailman.5.1733230566.2965.python-list@python.org>
References : 1 2 3
Roel Schroeven <roel@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


Date Sujet#  Auteur
3 Dec 24 o Re: super().__init__() and bytes1Anders Munch

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal