Initialization of variables using no-arg constructor

Edward Waugh edward_waugh at hotmail.com
Mon Oct 9 18:05:41 EDT 2006


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