[Tutor] subtyping builtin type

eryksun eryksun at gmail.com
Tue Dec 31 16:38:59 CET 2013


On Tue, Dec 31, 2013 at 9:35 AM, spir <denis.spir at gmail.com> wrote:
>
> I[n] particular, how does python know which param to take as
> source string? (There could be other params to __init__.)

You override __new__, and you might also have to override __init__,
but not in this case. object.__init__ ignores the extra args because
__new__ isn't object.__new__.

Since you're using 3.x, str.__new__ can take optional arguments for
bytes `encoding` and `errors`. You may want to preserve this feature
as keyword arguments. For example:

    class Source(str):
        __slots__ = ['i', 'n']
        def __new__(cls, s, i, n, **kwds):
            self = super(Source, cls).__new__(cls, s, **kwds)
            self.i = i
            self.n = n
            return self

    >>> Source(b'abc', 0, 3) # probably wrong
    "b'abc'"

    >>> Source(b'abc', 0, 3, encoding='ascii')
    'abc'


More information about the Tutor mailing list