[Tutor] subtyping builtin type
Zachary Ware
zachary.ware+pytut at gmail.com
Tue Dec 31 16:03:26 CET 2013
On Tue, Dec 31, 2013 at 8:35 AM, 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__.)
>>> class Source(str):
... __slots__ = ['i', 'n']
... def __init__(self, string):
... self.i = 0
... self.n = len(string)
...
>>> s = Source('testing')
>>> s
'testing'
>>> s.i
0
>>> s.n
7
If you look at the repr of str.__init__, you'll see that it is
inherited from object:
>>> str.__init__
<slot wrapper '__init__' of 'object' objects>
>>> str.__init__ is object.__init__
True
Compare this to the __init__ of list, which is a mutable type:
>>> list.__init__
<slot wrapper '__init__' of 'list' objects>
>>> list.__init__ is not object.__init__
True
Being immutable, str uses __new__ to create a new str object; it
doesn't use __init__ at all. Since you're not overriding __new__ in
your subclass, you don't need to worry about calling str.__new__
because it's already done by the time Source.__init__ is called.
HTH,
--
Zach
More information about the Tutor
mailing list