Sunday, August 23, 2015

Python on the go - Revision of Class and Inheritance

Referred from https://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes


  A class can be defined as a template for creating objects such as functions. For example the program below provides a description of a shape  and what operations you can do with the shape (that is, the functions). The  __init__()  function is always run when the class is called.

class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.description = "This shape has not been described yet"
        self.author = "Nobody has claimed to make this shape yet"
        
        
    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def describe(self, text):
        self.description = text

    def authorName(self, text):
        self.author = text

    def scaleSize(self, scale):
        self.x = self.x * scale
        self.y = self.y * scale



rectangle = Shape(100, 45)      #calling the class Shape
print rectangle.area()                # the area of the rectangle:

print rectangle.perimeter()       #the perimeter of it:

rectangle.scaleSize(0.5)         #makes it 50% smaller
print rectangle.area()              #the new area of the rectangle


It is possible to add extra features to a new class by using inheritance. The example below shows how a new class has inherited some of the features of the old one but its  __init__() function has changed.


class Square(Shape):
    def __init__(self,x):
        self.x = x
        self.y = x
        
square1=Square(10)
print square1.area()


No comments:

Post a Comment