Colin J. Williams wrote:
This prompts a similar query. __new__ appears to be intended for immutable objects but it seems to be called as part of constructor process for all instances.

That's because Python has no builtin way of determining whether or not a given type is immutable. If you wanted to, you could define both __new__ and __init__, the first to set immutable parts and the second to set mutable parts, e.g.:


py> class PartlyMutableTuple(tuple):
...     def __new__(cls, *args, **kwargs):
...         return super(PartlyMutableTuple, cls).__new__(cls, args)
...     def __init__(self, *args, **kwargs):
...         self.__dict__.update(kwargs)
...
py> t = PartlyMutableTuple(1, 2, 3, a=4, b=5)
py> t
(1, 2, 3)
py> t.a, t.b
(4, 5)
py> t.a, t.b = t.b, t.a
py> t.a, t.b
(5, 4)
py> t[0] = 2
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: object does not support item assignment

I don't think I'd advise this strategy, but by always calling both __new__ and __init__, Python makes it possible...

Steve
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to