473,386 Members | 1,803 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Initialization of variables using no-arg constructor

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
Oct 9 '06 #1
2 1358
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.
More natural would be (untested):

def sum(list):
assert list # both versions fail if list is empty
total = list[0]

# could use list[1:] but this avoids copying
for i in xrange(1, len(list)):
total += list[i]

or various alternate spellings with iterators, the reduce function, etc.

This pattern is common enough that Haskell has a "foldl1" function
similar to reduce but initializing from the first element of the sequence.
Oct 9 '06 #2
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
Oct 10 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: lovecreatesbea... | last post by:
K&R 2, sec 2.4 says: If the variable in question is not automatic, the initialization is done once only, conceptually before the program starts executing, ... . "Non-automatic variables are...
5
by: Jesper Schmidt | last post by:
When does CLR performs initialization of static variables in a class library? (1) when the class library is loaded (2) when a static variable is first referenced (3) when... It seems that...
3
by: Steve Folly | last post by:
Hi, I had a problem in my code recently which turned out to be the 'the "static initialization order fiasco"' problem (<http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12>) The FAQ...
17
by: copx | last post by:
I don't know what to think of the following.. (from the dietlibc FAQ) Q: I see lots of uninitialized variables, like "static int foo;". What gives? A: "static" global variables are initialized...
23
by: copx | last post by:
I don't know what to think of the following.. (from the dietlibc FAQ) Q: I see lots of uninitialized variables, like "static int foo;". What gives? A: "static" global variables are initialized...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.