0% found this document useful (0 votes)
25 views

HH IIMC PythonBasics s2

This document discusses classes and methods in Python. It provides examples of defining classes like Square and Rectangle with methods to calculate perimeter and area. It shows initializing classes like Student with attributes passed as parameters. It also demonstrates subclassing where Student inherits from Child, allowing objects to access attributes from both classes.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

HH IIMC PythonBasics s2

This document discusses classes and methods in Python. It provides examples of defining classes like Square and Rectangle with methods to calculate perimeter and area. It shows initializing classes like Student with attributes passed as parameters. It also demonstrates subclassing where Student inherits from Child, allowing objects to access attributes from both classes.

Uploaded by

Suresh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

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

You might also like