Exercise 6.2 - Solution

(a) Simple Properties

class Stock(object):
    '''
    An instance of a stock holding consisting of name, shares, and price.
    '''
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

    @property
    def cost(self):
        '''
        Return the cost as shares*price
        '''
        return self.shares * self.price

(b) Properties and Setters

class Stock(object):
    '''
    An instance of a stock holding consisting of name, shares, and price.
    '''
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

    @property
    def shares(self):
        return self._shares

    @shares.setter
    def shares(self, value):
        if not isinstance(value, int):
            raise TypeError("Must be an integer")
        self._shares = value

    @property
    def cost(self):
        '''
        Return the cost as shares*price
        '''
        return self.shares * self.price

(c) Slots

class Stock(object):
    '''
    An instance of a stock holding consisting of name, shares, and price.
    '''
    __slots__ = ('name', '_shares', 'price')
    def __init__(self, name, shares, price):
        self.name = name
        self.shares = shares
        self.price = price

    @property
    def shares(self):
        return self._shares

    @shares.setter
    def shares(self, value):
        if not isinstance(value, int):
            raise TypeError("Must be an integer")
        self._shares = value

    @property
    def cost(self):
        '''
        Return the cost as shares*price
        '''
        return self.shares * self.price

[ Back ]