Python Basics
Classes overview in Python
Methods in classes
class Square():
def perimeter(self,side):
return side*4
a = Square()
print a.perimeter(14)
**********************
class Student():
def __init__(self,name):
self.name = name Note
__init__(self,name) means that we must pass a parameter while making an object
a = Student("Sam") of the 'Student' class (or we must pass a value for the name while making an object
of the 'Student' class).
print a.name self.name = name : 'name' in 'self.name' is an attribute. It implies that the Student
class will have some attribute 'name' whereas 'name' on the right side of '=' is the
parameter that we will pass
**********************
Methods in classes
class Rectangle():
def __init__(self,l,b):
self.length = l
self.breadth = b
def getArea(self):
return self.length*self.breadth
def getPerimeter(self):
return 2*(self.length+self.breadth)
a = Rectangle(2,4)
print a.getArea()
Subclass of a class
class Child():
def __init__(self,name):
self.name = name
class Student(Child):
def __init__(self,name,roll):
self.roll = roll
Child.__init__(self,name)
a = Child("xyz")
print a.name
b = Student("abc",12)
print b.name
print b.roll
If we wouldn't have an initializer in the Student class, it would have used its Child's initializer and
we would have made objects by just passing the 'name'(a parameter). An example is given below
class Child():
def __init__(self,name):
self.name = name
class Student(Child):
pass
a = Child("xyz")
print a.name
b = Student("abc")
print b.name