Definition and test function for class Cylinder. : subclass « Class « Python Tutorial






import math

class Point:
   def __init__( self, xValue = 0, yValue = 0 ):
      self.x = xValue
      self.y = yValue

class Circle( Point ):
   def __init__( self, x = 0, y = 0, radiusValue = 0.0 ):
      Point.__init__( self, x, y )  # call base-class constructor
      self.radius = float( radiusValue )

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

   def __str__( self ):
      return "Center = %s Radius = %f" % ( Point.__str__( self ), self.radius )


class Cylinder( Circle ):
   def __init__( self, x, y, radius, height ):
      Circle.__init__( self, x, y, radius )
      self.height = float( height )

   def area( self ):
      return 2 * Circle.area( self ) + 2 * math.pi * self.radius * self.height

   def volume( self ):
      return Circle.area( self ) * height

   def __str__( self ):
      return "%s; Height = %f" % ( Circle.__str__( self ), self.height )


cylinder = Cylinder( 12, 23, 2.5, 5.7 )

print "X coordinate is:", cylinder.x
print "Y coordinate is:", cylinder.y
print "Radius is:", cylinder.radius
print "Height is:", cylinder.height

cylinder.height = 10
cylinder.radius = 4.25
cylinder.x, cylinder.y = 2, 2
print "\nThe new points, radius and height of cylinder are:", cylinder

print "\nThe area of cylinder is: %.2f" % cylinder.area()

print "\ncylinder printed as a Point is:", Point.__str__( cylinder )

print "\ncylinder printed as a Circle is:", Circle.__str__( cylinder )








11.29.subclass
11.29.1.Creating Subclasses
11.29.2.Class Inheritance
11.29.3.__bases__ Class Attribute
11.29.4.Overriding Methods through Inheritance
11.29.5.__init__() is not invoked automatically when the subclass is instantiated.
11.29.6.Deriving Standard Types
11.29.7.Mutable Type Example
11.29.8.Definition and test function for class Cylinder.