[Tutor] subtyping builtin type
Zachary Ware
zachary.ware+pytut at gmail.com
Tue Dec 31 16:54:57 CET 2013
On Tue, Dec 31, 2013 at 9:22 AM, spir <denis.spir at gmail.com> wrote:
> 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?
The interactive interpreter is great for this kind of thing, you know
;). I didn't know the answer to this question right off, so here's
what I tried:
>>> class Source(str):
... __slots__ = ['i', 'n', 'a', 'k']
... def __init__(self, *args, **kwargs):
... self.i = 0
... self.n = len(self)
... self.a = args
... self.k = kwargs
...
>>> s = Source('testing')
>>> s
'testing'
>>> s.i
0
>>> s.n
7
>>> s.a
('testing',)
>>> s.k
{}
>>> s = Source('testing', 'tester', b='kwarg test')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: 'b' is an invalid keyword argument for this function
>>> s = Source('testing', 'tester')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: decoding str is not supported
So it seems the answer is: if you want Source to be able to take args
that str doesn't, you'll have to define __new__ and intercept the
arguments you want (or the arguments meant for str) and pass only
str's arguments to str.__new__ to get self. Depending on what you're
trying to do, it may turn out easier (and less confusing) to not
subclass str at all, and just keep a _string attribute for the string.
--
Zach
More information about the Tutor
mailing list