[Tutor] subtyping builtin type

spir denis.spir at gmail.com
Tue Dec 31 16:22:31 CET 2013


On 12/31/2013 04:03 PM, Zachary Ware wrote:
> 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.

Thank you, Oscar & Zachary. I guess thus the way it is done is correct (for my 
case), is it? Seems your last remark shows the source of my confusion: probably, 
in past times, I subtyped builtin types and overrided their __new__, thus had to 
call the original one.
Would I have to do this if Source had other __init__ params? Or would it work 
anyway provided the string remains 1st param? Or what else?

Denis


More information about the Tutor mailing list