[Python-Dev] subclassing builtin data structures (original) (raw)

Neil Girdhar mistersheik at gmail.com
Sat Feb 14 02:16:08 CET 2015


I think it works as Isaac explained if make_me is an instance method that also accepts the calling class type.

On Fri, Feb 13, 2015 at 8:12 PM, Ethan Furman <ethan at stoneleaf.us> wrote:

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.makeme(int(self) + int(other)) > > ... def repr(self): > ... return 'A(%d)' % self How would this help in the case of defaultdict? makeme is a class method, but it needs instance info to properly create a new dict with the same default factory. -- Ethan


Python-Dev mailing list Python-Dev at python.org https://mail.python.org/mailman/listinfo/python-dev Unsubscribe: https://mail.python.org/mailman/options/python-dev/mistersheik%40gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-dev/attachments/20150213/2f1897b8/attachment-0001.html>



More information about the Python-Dev mailing list