Friday 12 April 2013

A Python counter. Using it for colour incrementing.


class z:

    """Counter.  My first!  

    Instantiate with number of items between 0 and 1.
    Calling the class will return an incrementing value.

    """


    def __init__(self, n):
        self.n = n
        self.i = -1

    def __call__(self):
        """This gets called when the instantiated object is called"""
        if self.i == self.n:
            raise StopIteration
        self.i += 1
        return self.i * 1.0 / (self.n - 1)

Use as,

In [1]:  a = z(10)

In [2]:  print a(), a(), a(), a(), a(), a(), a(), a(), a(), a()

         0.0 0.111 0.222 0.333 0.444 0.555 0.666 0.777 0.888 1.0

(Those results are truncated ;) )

Use to control colour as,

from matplotlib import cm
a = z(10)
plot(x, y, color=cm.jet(a))
plot(x2, y2, color=cm.jet(a))
plot(x3, y3, color=cm.jet(a))

No comments:

Post a Comment