python class example
Python class is defined by using the keyword class. Class properties are defined by using the keyword self and Class constructor is defined by using __init__. __str__ is similar to the toString function in other programming languages such as Java.
#!/usr/bin/env python # Cylinder class, with properties of radius and height class Cylinder: def __init__(self,radius,height): self.radius = radius self.height = height def __str__(self): return "Radius: "+ str(self.radius) + ", Height: " + str(self.height) def getRadius(self): return self.radius def getHeight(self): return self.height def getVolume(self): return self.radius*self.radius*3.14*self.height #Creating a cylinder object from the Cylinder class cd=Cylinder(5,10) print "A Cylinder with" print "Radius: "+str(cd.getRadius()) print "Height: "+ str(cd.getHeight()) print cd # This will call the function __str__ print "It's volume is "+str(cd.getVolume())
Output:
A Cylinder with Radius: 5 Height: 10 Radius: 5, Height: 10 It's volume is 785.0
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts