Press "Enter" to skip to content

Python Notes 7 : Writing Classes & Special Methods

Everything in python is an Object. We can use type function to check the type of any object in python.

A Sample class in python looks like –

class Circle(object):
    pi = 3.14

    # Circle get instantiated with a radius (default is 1)
    def __init__(self, radius=1):
        self.radius = radius 

    # Area method calculates the area. Note the use of self.
    def area(self):
        return self.radius * self.radius * Circle.pi

    # Method for resetting Radius
    def setRadius(self, radius):
        self.radius = radius

    # Method for getting radius (Same as just calling .radius)
    def getRadius(self):
        return self.radius


c = Circle()
c.setRadius(2)
print 'Radius is: ',c.getRadius()
print 'Area is: ',c.area()

Output –¬†

Radius is:  2
Area is:  12.56

Special Methods
class Book(object):
    def __init__(self, title, author, pages):
        print "A book is created"
        self.title = title
        self.author = author
        self.pages = pages

    def __str__(self):
        return "Title:%s , author:%s, pages:%s " %(self.title, self.author, self.pages)

    def __len__(self):
        return self.pages

    def __del__(self):
        print "A book is destroyed"

book = Book("Python Rocks!", "Jose Portilla", 159)
#Special Methods
print book
print len(book)
del book

Output
A book is created
Title:Python Rocks! , author:Jose Portilla, pages:159 
159
A book is destroyed

								

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *