Joy Diamond <python....@gmail.com> added the comment:

Its quite valid to assign to __new__ to replace the behavior of how an instance 
is created.

(Obviously you would not really assign `0` to it; my example was just to show 
the `del Color.__new__` fails - so what was assigned was not relevant).

Here is a more realistic assignment to __new__ -- this one shows we are 
"caching" the instance "green" -- so it is reused:

class Color(object):
    __slots__ = (('name',))

    def __init__(self, name):
        self.name = name


green = Color('green')  #   Works
assert green.name == 'green'


@staticmethod
def Color__new__cache_green(m, name):
    if name == 'green':
        return green

    return object.__new__(m, name)


Color.__new__ = Color__new__cache_green

green_2 = Color('green')
assert green_2 == green

blue = Color('blue')
assert blue.name == 'blue'

del Color.__new__

red = Color('red')      #   Fails in Python 3; works in Python 2 & pypy
assert red.name == 'red'

Finally as for `Color.__x__` assignment, this has nothing to do with 
`__slots__` as it is assigning to `Color`, not to an instance of `Color`.

`green.__x__ = 0` properly fails since there is no `__x__` slot:

AttributeError: 'Color' object has no attribute '__x__'

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35098>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to