class Circle(object): # new-style class
"""An advanced circle analytic toolkit"""
version = "0.1"
spam = 0.5
def __init__(self, radius):
self.radius = radius
def area(self):
"Perform quadrature on this circle."
return 3.14 * self.radius ** 2
Regular methods have "self" as their first argument.
Hmmm, what about the '3.14'?
from random import random, seed
from circle import Circle
seed(8675309)
print 'Using Circuitous(tm) version', Circle.version
n = 10
circles = [Circle(random()) for i in xrange(n)]
print 'The average area of', n, 'random circles'
avg = sum([c.area() for c in circles]) / n
print 'is %1.f' % avg
print
import math
class Circle(object): # new-style class
"""An advanced circle analytic toolkit"""
version = "0.1"
spam = 0.5
def __init__(self, radius):
self.radius = radius
def area(self):
"Perform quadrature on this circle."
return math.pi * self.radius ** 2
def perimeter(self):
"Find the circle's perimeter."
return 2.0 * math.pi * self.radius
from circle import Circle
cuts = [0.1, 0.7, 0.8]
circles = [Circle(r) for r in cuts]
for c in circles:
print 'A circlet with a radius of', c.radius
print 'has a perimeter of', c.perimeter()
print 'and a cold area of', c.area()
c.radius *= 1.1
print 'and a warm area of', c.area()
print
Notice what happens to the radius attribute here!
from circle import Circle
class Tire(Circle):
"Tires are circles with a corrected perimeter."
def perimeter(self):
"Circumference corrected for the tire width."
return Circle.perimeter(self) * 1.25
t = Tire(22)
print 'A tire of radius', t.radius
print 'has an inner area of', t.area()
print 'and an odometer corrected perimeter of',
print t.perimeter()
print
from circle import Circle
bbd = 25.1
c = Circle(bbd_to_radius(bbd))
print 'A circle with a bbd of 25.1'
print 'has a radius of', c.radius
print 'and an area of', c.area()
print
Their comment: the API is awkward - a converter function is needed.
Perhaps change the constructor?