Methods:


In [50]:
class Circle(object):
    # class object attribute
    pi = 3.14
    
    def __init__(self, radius=1):
        self.radius = radius
        
    def area(self):
        return Circle.pi * (self.radius**2)
    
    def set_radius(self, new_radius):
        """
        This method takes input as new_radius and resets the old radius to new_radius
        """
        self.radius = new_radius
        
    def get_radius(self):
        return self.radius
    
    def get_perimeter(self):
        return 2.0 * Circle.pi * self.radius

In [51]:
m_circle = Circle(5)

In [52]:
m_circle.area()


Out[52]:
78.5

In [53]:
m_circle.set_radius(15)

In [54]:
m_circle.radius


Out[54]:
15

In [55]:
m_circle.get_radius()


Out[55]:
15

In [56]:
m_circle.area()


Out[56]:
706.5

In [57]:
m_circle.get_perimeter()


Out[57]:
94.2

Inheritance


In [4]:
class Animal(object):
    
    def __init__(self):
        print 'Animal created'
    
    def whoAmI(self):
        print 'Animal'
    
    def eat(self):
        print 'Eating'

In [5]:
m_animal = Animal()


Animal created

In [17]:
class Dog(Animal):
    def __init__(self):
        Animal.__init__(self)
        print 'Dog created'
        
    def whoAmI(self):
        print 'Dog'
    
    def bark(self):
        print 'woof'

In [18]:
m_dog = Dog()


Animal created
Dog created

In [19]:
m_dog.whoAmI()


Dog

In [20]:
m_dog.eat()


Eating

In [16]:
m_dog.bark()


woof

Special Methods


In [48]:
class Book(object):
    def __init__(self, title, author, pages):
        print "A book has been created!!!!"
        self.title = title
        self.author = author
        self.pages = pages
    
    # special methods
    
    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 "Book is deleted!"

In [49]:
m_book = Book('Long fight', 'rustomPotter217', 217)


A book has been created!!!!

In [50]:
print m_book


Title: Long fight, Author: rustomPotter217, pages: 217

In [51]:
len(m_book)


Out[51]:
217

In [52]:
del(m_book)


Book is deleted!

In [53]:
# homework-1

In [69]:
class Line(object):
    def __init__(self, coor1, coor2):
        self.coor1 = coor1
        self.coor2 = coor2
        self.x1, self.y1 = self.coor1
        self.x2, self.y2 = self.coor2
    
    def distance(self):
        #x1, y1 = self.coor1
        #x2, y2 = self.coor2
        return ((self.x1-self.x2)**2 + (self.y1-self.y2)**2)**0.5
    
    def slope(self):
        return ((self.x2 - self.x1)/(self.y2 - self.y1));

In [70]:
m_line = Line((1,1), (8,2.5))

In [71]:
m_line.distance()


Out[71]:
7.158910531638177

In [72]:
m_line.slope()


Out[72]:
4.666666666666667

In [ ]: