[Tutor] Better structure?

Alan Gauld alan.gauld at freenet.co.uk
Thu Feb 3 09:41:22 CET 2005

> > Try writing the code to do what lstrip actually does
> > - its much harder. So the library includes the more
> > difficult function and lets you code the easy ones.
> def lstrip(string,chars=' ')
>     string = list(string)
>     t = 0
>     for x in string:
>         if x in chars:
>             string.remove(t)
>         else:
>             break
>         t = t+1
> Okay, so it's not that difficult, but I get your point.

I assume you didn't try testing that.
It doesn't work. Its close but there are some extra wrinkles
you need to consider. And its the wrinkles that makes writing
library code hard! But even this is more complex than the
simple front slicing that you were looking for.

[As an aside, estimates vary, but it is reckoned to take between 5-10
times as much effort to write generic reusable code as it does to
write specific code. One of the things proponents of the argument
that "reuse is cheap" often forget! Its only cheap if someone
else develops what you reuse!]

> to a different module. Unfortunately, they are quite random and I
will have
> to find someway of seperating them.

And another hard part of designing any library is figuring out
the best logical structure, which module has which bits.

> Uck. True usually in printing. String formatting doesn't cut it for
a type
> that's not a string. Especially something not builtin.

It does if you override the __Str__ method of your newly defined type.
Then you can print it using %s...  Although you did trigger the
interesting thought: I wonder if there is a way of hooking the
formatting characters to tailor the representation, hmmm,
some research required...

> >You can even subclass string and make it a method if you like.
> Ooooh! How do I do that?

class MyString(string):
   # your methods go here, and don't forget __init__...


Alan G.

More information about the Tutor mailing list