Subclassing str object

Ian Kelly ian.g.kelly at gmail.com
Wed Aug 31 19:11:16 CEST 2011


2011/8/31 Yaşar Arabacı <yasar11732 at gmail.com>:
> I made a class like this (I shortened it just to show the point), what do
> you think about it, do you think it is the python way of subclassing str (or
> unicode in this case)

You don't need the _sozcuk attribute at all here.  It's just the same
as the value of the unicode object itself.  The code could be
simplified to:

class kelime(unicode):

    def __getattribute__(self, isim):
        att = super(kelime, self).__getattribute__(isim)
        if not callable(att):
            return att
        def sonra_cagir(*args, **kwargs):
            sonuc = att(*args, **kwargs)
            if isinstance(sonuc, basestring):
                return kelime(sonuc)
            return sonuc
        return sonra_cagir

    def cogul(self):
        for harf in reversed(self):
            if harf in kalin:
                return kelime(self + u"lar")
            elif harf in ince:
                return kelime(self + u"ler")
        return kelime(self + u"lar")

Also, "isinstance(sonuc, basestring)" should probably be
"isinstance(sonuc, unicode)".  Otherwise you'll break the encode
method.

If you want "kelime(u'one') + kelime(u'two')" to return a kelime
instance, you'll need to override the __add__ special method as well.
Likewise for "kelime(u'repeat') * 20" and the __mul__ method.  You'll
also want to override __getitem__ so that slicing returns a kelime
instance as expected.

Finally, I gather that the goal of this is not to modify the behavior
of the unicode class at all, but just to add custom methods?  I would
strongly recommend that you not use a subclass for this, and instead
just write some functions that take a string to operate on as an
argument.  Subclassing built-in types tends to be tricky as you can
see, and this doesn't seem like a good reason to attempt it.

Cheers,
Ian



More information about the Python-list mailing list