Initialization of variables using no-arg constructor

jordanrastrick at gmail.com jordanrastrick at gmail.com
Tue Oct 10 03:07:35 EDT 2006


Just to expand a little on what others have already said - not only is
the total = list[0] etc.approach more readable, idiomatic, and elegant,
IMO its more semantically correct.

Your constraint that list[0].__class__ has a no-arg constructor is not
strong enough; a more subtle and potentially bug-prone assumption youre
making is that this no-arg constructor returns an identity element
(something that when added doesnt affect your overall "total") with
respect to the addition operator. This happens to be true of summing
numbers (__class__ == 0), and concatenating strings (__class__() ==
""). But I don't think you can take this behaviour for granted from an
arbitrary class.

Edward Waugh wrote:
> Consider the following (working) Python code:
>
> import sys
>
> def sum(list):
>     # total = 0 does not work for non-numeric types
>     total = list[0].__class__()
>     for v in list:
>         total += v
>     return total
>
> l = [1, 2, 3]
> print sum(l)
>
> l = [1.1, 2.2, 3.3]
> print sum(l)
>
> l = ["a", "b", "c"]
> print sum(l)
>
> In order for sum() to be generic I initialize total to the value of
> list[0].__class__().  This works but I would like to know if this is the
> correct or preferred way of doing it.  It means that sum() must be given a
> list whose elements are types or classes that have a no-arg constructor
> (through this is probably almost always the case).
> 
> Thanks,
> Edward




More information about the Python-list mailing list