Decorators part 2: using decorators inside a class

Date: February 15th 2016
Last updated: February 15th 2016

Decorators can be used inside a class and executed as a main program or from importing in a python shell.

# decorator to pretty print
def formatter(func):
    def inner(*args):
         return "{} = {:.2f}".format(func.__name__, func(*args))
    return inner

class Circle(object):
    """create a circle and calculate attributes"""
    def __init__(self, radius, height):
        self.radius = float(radius)
        self.height = float(height)

    @formatter
    def diameter(self):
        return self.radius * 2

    @formatter
    def area(self):
        return (math.pi * self.radius) ** 2

    @formatter
    def perimeter(self):
        return (2 * math.pi) * self.radius

    @formatter
    def cone_volume(self):
        return 1/3 * (math.pi * (self.radius ** 2)) * 
                self.height

    @formatter
    def cone_area(self):
        return math.pi * self.radius * (self.radius +
                math.sqrt(self.height**2 + self.radius**2))

if __name__ == "__main__":
    import math, sys
    circ = Circle(sys.argv[1], sys.argv[2])
    print(circ.diameter())
    print(circ.area())
    print(circ.perimeter())

results matching ""

    No results matching ""