Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12502

Re: Subclassing str object

References <CAFEUn8Z-9Qn=ZXS7e7C4AsNg=YOo78Jd5tca1_VkHRsfLyD1Aw@mail.gmail.com> <CAFEUn8YYTVeADOsZz+t24zsycNNyETYt-3m2ctZ_cYcPs-XT=w@mail.gmail.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2011-08-31 11:11 -0600
Subject Re: Subclassing str object
Newsgroups comp.lang.python
Message-ID <mailman.618.1314810707.27778.python-list@python.org> (permalink)

Show all headers | View raw


2011/8/31 Yaşar Arabacı <yasar11732@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Subclassing str object Ian Kelly <ian.g.kelly@gmail.com> - 2011-08-31 11:11 -0600

csiph-web