Message328782
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__' |
|
Date |
User |
Action |
Args |
2018-10-29 01:43:26 | joydiamond | set | recipients:
+ joydiamond, steven.daprano |
2018-10-29 01:43:26 | joydiamond | set | messageid: <1540777406.8.0.788709270274.issue35098@psf.upfronthosting.co.za> |
2018-10-29 01:43:26 | joydiamond | link | issue35098 messages |
2018-10-29 01:43:26 | joydiamond | create | |
|