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

[Python-Dev] subclassing builtin data structures

[Python-Dev] subclassing builtin data structuresNick Coghlan ncoghlan at gmail.com
Sat Feb 14 10:44:19 CET 2015
On 14 Feb 2015 08:57, "Alexander Belopolsky" <alexander.belopolsky at gmail.com>
wrote:
>
>
> On Fri, Feb 13, 2015 at 4:44 PM, Neil Girdhar <mistersheik at gmail.com>
wrote:
>>
>> Interesting:
http://stackoverflow.com/questions/5490824/should-constructors-comply-with-the-liskov-substitution-principle
>
>
> Let me humbly conjecture that the people who wrote the top answers have
background in less capable languages than Python.
>
> Not every language allows you to call self.__class__().  In the languages
that don't you can get away with incompatible constructor signatures.
>
> However, let me try to focus the discussion on a specific issue before we
go deep into OOP theory.
>
> With python's standard datetime.date we have:
>
> >>> from datetime import *
> >>> class Date(date):
> ...     pass
> ...
> >>> Date.today()
> Date(2015, 2, 13)
> >>> Date.fromordinal(1)
> Date(1, 1, 1)
>
> Both .today() and .fromordinal(1) will break in a subclass that redefines
__new__ as follows:
>
> >>> class Date2(date):
> ...     def __new__(cls, ymd):
> ...         return date.__new__(cls, *ymd)
> ...
> >>> Date2.today()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: __new__() takes 2 positional arguments but 4 were given
> >>> Date2.fromordinal(1)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: __new__() takes 2 positional arguments but 4 were given
>
> Why is this acceptable, but we have to sacrifice the convenience of
having Date + timedelta
> return Date to make it work  with Date2:
>
> >>> Date2((1,1,1)) + timedelta(1)
> datetime.date(1, 1, 2)

Coupling alternative constructors to the default constructor signature is
pretty normal - it just means that if you override the signature of the
default constructor, you may need to update the alternative ones
accordingly.

Cheers,
Nick.



>
>
>
> _______________________________________________
> 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/ncoghlan%40gmail.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20150214/873ebf0d/attachment.html>
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