[Tutor] subtyping builtin type

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Dec 31 16:01:42 CET 2013


On Dec 31, 2013 2:37 PM, "spir" <denis.spir at gmail.com> wrote:
>
> Hello,
>
> I don't remember exactly how to do that. As an example:
>
> class Source (str):
>     __slots__ = ['i', 'n']
>     def __init__ (self, string):
>         self.i = 0                  # current matching index in source
>         self.n = len(string)        # number of ucodes (Unicode code
points)
>         #~ str.__init__(self, string)
>
> I thought I needed to call str's __init__, as in the line comented out,
but (1) python refuses with a TypeError (2) all seems to work fine
(meaning, the string is well stored, *implicitely*). Am I missing some
point, or is this the way to do? How does it work? I particular, how does
python know which param to take as source string? (There could be other
params to __init__.)

The underlying built-in object is created by str.__new__ before __init__ is
called. If you override __new__ you'll need to defer to str.__new__ and can
choose to intercept the arguments and replace them.

Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131231/9538064f/attachment.html>


More information about the Tutor mailing list