Exercise 10.1

Objectives:

  • Variable argument passing.

Files Modified: None

(a) A simple example of variable arguments

Try defining the following function:

>>> def avg(x,*more):
        return float(x+sum(more))/(1+len(more))

>>> avg(10,11)
10.5
>>> avg(3,4,5)
4.0
>>> avg(1,2,3,4,5,6)
3.5
>>>

Notice how the parameter *more collects all of the extra arguments.

(b) Passing a tuple as arguments

Suppose you read some data from a file and obtained a tuple such as this:

>>> data = ('GOOG',100,490.10)
>>>

Now, suppose you wanted to create a Stock object from this data. If you just try to pass ``data`` directly, it doesn’t work:

>>> from stock import Stock
>>> s = Stock(data)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 4 arguments (2 given)
>>>

This is easily fixed using ``*data`` instead. Try this:

>>> s = Stock(*data)
>>>

(c) Creating a list of instances

Try reading a portfolio into a list of dictionaries using either your report.py program or fileparse.py. For example:

>>> import report
>>> portfolio = report.read_portfolio('Data/portfolio.csv')
>>> for s in portfolio:
       print s

... inspect the contents ...
>>>

Suppose you wanted to convert the entire list into a list of Stock instances. Here’s one way to do it:

>>> portfolio = [Stock(**s) for s in portfolio]
>>> for s in portfolio:
       print s

... look at the output ...
>>>

In this example, the **s turns dictionaries into keyword arguments that are passed to the Stock.__init__() function. It works because the dictionary keys have the same names as the arguments to Stock.__init__().

(d) Updating object attributes

Define the following function that allows you to update multiple attributes of an object at once:

>>> def update(obj, **kwargs):
        for name, val in kwargs.items():
            if hasattr(obj, name):
                setattr(obj, name, val)
            else:
                raise AttributeError('No such attribute: %s' % name)

>>> s = Stock('GOOG', 100, 490.1)
>>> s
Stock('GOOG', 100, 490.1)
>>> update(s, shares=50, price=385.23)
>>> s
Stock('GOOG', 50, 385.23)
>>> update(s, share=50)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in update
AttributeError: No such attribute: share
>>>
Links