A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2015-February/138249.html below:

[Python-Dev] subclassing builtin data structures

[Python-Dev] subclassing builtin data structuresSerhiy Storchaka storchaka at gmail.com
Fri Feb 13 23:31:14 CET 2015
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).

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
...
>>> A.__make_me__ = A
>>> A(2) + 3
A(5)
>>> class B(A):
...     def __repr__(self):
...         return 'B(%d)' % self
...
>>> B.__make_me__ = B
>>> B(2) + 3
B(5)

We can add special attribute used to creating results of operations to 
all basic classes. By default it would be equal to the base class 
constructor.

More information about the Python-Dev mailing list

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4