[Python-Dev] subclassing builtin data structures
Ethan Furman
ethan at stoneleaf.us
Sat Feb 14 02:12:42 CET 2015
On 02/13/2015 02:31 PM, Serhiy Storchaka wrote:
> On 13.02.15 05:41, Ethan Furman wrote:
>> So there are basically two choices:
>>
>> 1) always use the type of the most-base class when creating new instances
>>
>> pros:
>> - easy
>> - speedy code
>> - no possible tracebacks on new object instantiation
>>
>> cons:
>> - a subclass that needs/wants to maintain itself must override all
>> methods that create new instances, even if the only change is to
>> the type of object returned
>>
>> 2) always use the type of self when creating new instances
>>
>> pros:
>> - subclasses automatically maintain type
>> - much less code in the simple cases [1]
>>
>> cons:
>> - if constructor signatures change, must override all methods which
>> create new objects
>
> And switching to (2) would break existing code which uses subclasses with constructors with different signature (e.g.
> defaultdict).
I don't think defaultdict is a good example -- I don't see any methods on it that return a new dict, default or
otherwise. So if this change happened, defaultdict would have to have its own __add__ and not rely on dict's __add__.
> The third choice is to use different specially designed constructor.
>
> class A(int):
>
> --> class A(int):
> ... def __add__(self, other):
> ... return self.__make_me__(int(self) + int(other))
>
> ... def __repr__(self):
> ... return 'A(%d)' % self
How would this help in the case of defaultdict? __make_me__ is a class method, but it needs instance info to properly
create a new dict with the same default factory.
--
~Ethan~
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150213/739dae36/attachment.sig>
More information about the Python-Dev
mailing list