Question about extending tuple

Georg Brandl g.brandl at gmx.net
Wed Mar 28 16:27:38 EDT 2007


abcd schrieb:
>> As an immutable type, tuple makes use of __new__.
>>
>> class MyTuple(tuple):
>>      def __new__(cls, *args):
>>          return tuple.__new__(cls, args)
>>
>> should work.
>>
>> Georg
> 
> strange.  not very consistent.

On the contrary -- __new__ *and* __init__ exist for all types.
The only difference is where a specific object is initialized, and
therefore which method you have to override.

__new__ is a static method (it doesn't need to be declared as one,
this is done automatically as it predates the introduction of
staticmethod()) which is called to *construct* an instance.
This can only be done once for a specific object since each call to
__new__ will result in a *new* object. In other words, this is
perfect for immutable objects -- once created, never changed.

__init__, OTOH, is called on the *instance* to initialize it. Of
course, this process can be repeated, and is therefore apt for
mutable objects like lists.

I hope you see now why it is consistent.

Georg




More information about the Python-list mailing list