Newbie question: how to join a list of elements of user-defined types?

holger krekel pyth at devel.trillke.net
Tue Apr 30 08:06:44 EDT 2002


On Mon, Apr 29, 2002 at 11:11:57PM -0400, Benjamin Han wrote:
> >
> > s = " ".join([str(i) for i in l])
> 
> This surely looks nicer. I'm just wondering how far Python has fared in terms 
> of this concept of OO? This example seems to show a very different character 
> of OO in Python, in that __str__ is not automatically called, which seems 
> rather counter-intuitive.

It doesn't seem counterintuitive to me (any more). You might be interested in 
reading about the design-principles of python here:

http://www.python.org/dev/culture.html

You will find that 'expliciteness' is valued very high. That's
a design decision which works out greatly, in my opionion.
There are always ways to increase convenience explicitely
without interfering with *the whole system*. Take your
example. You have a list that inherits from the list-type
in python. You want to join the elements using
a specified character. The *generic* string.join method
does not autoconvert for you (like c++ might do).  
But it is very easy to provide convenience:

class Mylist(type([])):
    def strjoin(self, char):
        return char.join(map(str, self))

and then calling

print Myline.strjoin(',')

Compare this to the pain of inheriting from
the C++-STL-sequence classes and defining appropriate
auto-conversion methods. Btw, i prefer to
inherit from 'type([])' to make it visible
that i am extending a basic type. 'list' could
be anything IMO. The Unification of Types and 
Objects is a recent development. See here
for reference:

http://www.python.org/peps/pep-0253.html

> Without private members, and with seemingly complex ways of dealing with class 
> members and methods - so what's the state of OO in Python? Is it still 
> rapidly evolving? How much is an effort in converting Python into C++? Anyone 
> would like to comment on some of these questions, or point to some article, 
> FAQ (esp. helpful from a C++ programmer's point of view)?

Coming from c++ i find it very useful to work my way through the various
PEPs (Python Enhancement Proposals). From time to time, not all at once :-)

http://www.python.org/peps/

There are probably other resources which others can point you too.

have fun,

    holger





More information about the Python-list mailing list