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


Groups > comp.lang.python > #197038

RE: super().__init__() and bytes

From Anders Munch <ajm@flonidan.dk>
Newsgroups comp.lang.python
Subject RE: super().__init__() and bytes
Date 2024-12-03 12:55 +0000
Message-ID <mailman.5.1733230566.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>

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar


Thread

RE: super().__init__() and bytes Anders Munch <ajm@flonidan.dk> - 2024-12-03 12:55 +0000

csiph-web