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/138187.html below:

[Python-Dev] subclassing builtin data structures

[Python-Dev] subclassing builtin data structuresMRAB python at mrabarnett.plus.com
Fri Feb 13 02:46:21 CET 2015
On 2015-02-13 00:55, Guido van Rossum wrote:
> On Thu, Feb 12, 2015 at 4:36 PM, Ethan Furman <ethan at stoneleaf.us
> <mailto:ethan at stoneleaf.us>> wrote:
>
>     I suspect the last big hurdle to making built-in data structures
>     nicely subclassable is the insistence of such types to
>     return new instances as the base class instead of the derived class.
>
>     In case that wasn't clear ;)
>
>     --> class MyInt(int):
>     ...   def __repr__(self):
>     ...     return 'MyInt(%d)' % self
>     ...
>     --> m = MyInt(42)
>     --> m
>     MyInt(42)
>     --> m + 1
>     43
>     --> type(m+1)
>     <class 'int'>
>
>     Besides the work it would take to rectify this, I imagine the
>     biggest hurdle would be the performance hit in always
>     looking up the type of self.  Has anyone done any preliminary
>     benchmarking?  Are there other concerns?
>
>
> Actually, the problem is that the base class (e.g. int) doesn't know how
> to construct an instance of the subclass -- there is no reason (in
> general) why the signature of a subclass constructor should match the
> base class constructor, and it often doesn't.
>
 > So this is pretty much a no-go. It's not unique to Python -- it's a
 > basic issue with OO.
 >
Really?


 >>> class BaseInt:
...     def __init__(self, value):
...         self._value = value
...     def __add__(self, other):
...         return type(self)(self._value + other)
...     def __repr__(self):
...         return '%s(%s)' % (type(self), self._value)
...
 >>> class MyInt(BaseInt):
...     pass
...
 >>>
 >>> m = BaseInt(42)
 >>> m
<class '__main__.BaseInt'>(42)
 >>> m + 1
<class '__main__.BaseInt'>(43)
 >>> type(m + 1)
<class '__main__.BaseInt'>
 >>>
 >>> m = MyInt(42)
 >>> m
<class '__main__.MyInt'>(42)
 >>> m + 1
<class '__main__.MyInt'>(43)
 >>> type(m + 1)
<class '__main__.MyInt'>
 >>>

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