arbitrary number of arguments in a function declaration

R

rbt

How do I set up a function so that it can take an arbitrary number of
arguments? For example, I have a bunch of expenses which may grow or
shrink depending on the client's circumstance and a function that sums
them up... hard coding them is tedious. How might I make this dynamic so
that it can handle any amount of expenses?

def tot_expenses(self, e0, e1, e2, e3):
pass
 
N

Nick Coghlan

rbt said:
How do I set up a function so that it can take an arbitrary number of
arguments? For example, I have a bunch of expenses which may grow or
shrink depending on the client's circumstance and a function that sums
them up... hard coding them is tedious. How might I make this dynamic so
that it can handle any amount of expenses?

def tot_expenses(self, e0, e1, e2, e3):
pass

The Python Tutorial is a wonderful thing. . .

Anyway, you can either set up your function to take a proper list, and then
discover that the sum function already exists to add up the contents of a list:

def tot_expenses(self, expenses):
self.total_expenses = sum(expenses)

Or, have the function take a variable number of arguments, and do the same thing:

def tot_expenses(self, *args):
self.total_expenses = sum(args)

Cheers,
Nick.
 
R

rbt

Nick said:
The Python Tutorial is a wonderful thing. . .

But so is this list ;)
Anyway, you can either set up your function to take a proper list, and
then discover that the sum function already exists to add up the
contents of a list:

def tot_expenses(self, expenses):
self.total_expenses = sum(expenses)

Or, have the function take a variable number of arguments, and do the
same thing:

def tot_expenses(self, *args):
self.total_expenses = sum(args)

Cheers,
Nick.

Many thanks!
 
S

Steven Bethard

rbt said:
How do I set up a function so that it can take an arbitrary number of
arguments?

If you haven't already, you should check out the Tutorial:

http://docs.python.org/tut/node6.html#SECTION006730000000000000000
How might I make this dynamic so
that it can handle any amount of expenses?

def tot_expenses(self, e0, e1, e2, e3):
pass

py> class C(object):
.... def tot_expenses(self, *expenses):
.... print expenses
....
py> C().tot_expenses(110, 24)
(110, 24)
py> C().tot_expenses(110, 24, 2, 56)
(110, 24, 2, 56)

Steve
 
I

it's me

And in case it's not obvious already, you get the number of arguments that
got passed down from:

len(args)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top