Python Module 5
Python Module 5
MODULE 5
SYLLABUS:
Classes and objects, Programmer-defined types, Attributes, Rectangles, Instances as return values,
Objects are mutable, Copying
Classes and functions, Time, Pure functions, Modifiers, Prototyping versus planning
Classes and methods, Object-oriented features, Printing objects, Another example, A more
complicated example,The init method, The str method, Operator overloading, Type-based
dispatch, Polymorphism, Interface and implementation,
Textbook: Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2nd
Edition, Green Tea Press, 2015. (Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf) (Chapters 13, 15, 16, 17, 18)
(Download pdf/html files from the above links)
• Object
• Reference Variable
Mould is a Class
Ganesha Idols are objects
Plan is a Class
Pan is a Class
Class
Object
• Object is the physical existence or an instance of class.
• We can create any number of objects to a class
Reference Variable
********** above examples are only for understanding the concept in a better way, don’t
write them in exam*************
Class:
A Class is like an object constructor, or a "blueprint" for creating objects.
A programmer-defined type is also called a class.
A class definition looks like this:
class Point:
"""Represents a point in 2-D space."""
>>>blank = Point()
>>>blank
Output:
< main .Point object at 0xb7e9d3ac>
• When you print an instance, Python tells you what class it belongs to and where it is stored
in memory (the prefix 0x means that the following number is in hexadecimal).
• The return value is a reference to a Point object, which we assign to blank.
Example 1:
Create a Class:
• To create a class, use the keyword class
Example:
class My Class:
x=5
Create Object:
• Now we can use the class named My Class to create objects
• Create an object named p1, and print the value of x
Example:
p1 = MyClass()
print(p1.x)
Complete Program
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
Output:
5
• The variable blank refers to a Point object, which contains two attributes.
1.2 Rectangles
Example:
class Rectangle:
‘ ‘ ‘ Doc String – Optional ’ ’ ’
box = Rectangle()
box. width = 100.0
box. height = 200.0
box. corner =
Point()box. corner.
x = 0.0
box. corner. y = 0.0
The expression box. corner. x means, “Go to the object box refers to and select
theattribute named corner; then go to that object and select the attribute named x.”
An object that is an attribute of another object is embedded.
1.3 Instances as return values
Functions can return instances.
For example, find_ center takes a Rectangle as an argument and returns a Point
thatcontains the coordinates of the center of the Rectangle:
Example :
class Point:
"""Represents a point in 2-D space."""
blank = Point()
blank. x = 3.0
blank. y = 4.0
class Rectangle:
'''Doc String – Optional'''
box = Rectangle()box.
width = 100.0
box. height = 200.0
p = Point()
p. x = rect. corner. x + rect. width/2
p. y = rect. corner. y + rect. height/2
Output:
(50, 100)
Example:
class Point:
"""Represents a point in 2-D space."""
blank = Point()
blank. x = 3.0
blank. y = 4.0
class Rectangle:
'''Doc String – Optional'''
box = Rectangle()
box. width = 100.0
box. height = 200.0
box. corner =Point()
box. corner. x = 0.0
box. corner. y = 0.0
p = Point()
p. x = rect. corner. x + rect. width/2
p. y = rect. corner.y+rect.height/2
return p
center = find_center(box)
print_point(center)
print(box.width,box.height)
Output:
75, 150
150.0 300.0
1.5 Copying
• Aliasing can make a program difficult to read because changes in one place might have
unexpected effects in another place.
• It is hard to keep track of all the variables that might refer to a given object.
• Copying an object is often an alternative to aliasing.
• The copy module contains a function called copy that can duplicate any object:
Complete Program:
class Time:
"""Represents the time of day.
attributes: hour, minute, second
"""
time = Time ()
time. hour = 11
time. minute = 59
time. second = 30
The state diagram for the Time object looks like
Pure Functions
Modifiers
• To understand the concept we will define a class called Time that records the time of day.
• The class definition looks like this and We can create a new Time object or instance, also
create and assign attributes for hours, minutes, and seconds.
• The function that creates a new Time object, initializes its attributes with new values and
returns a reference to the new object.
• This is called a pure function because it does not modify any of the objects passed to it as
arguments and it has no effect, like displaying a value or getting user input, other than
returning a value.
Pure functions example
class Time:
"""Represents the time of day. attributes: hour, minute, second""“
duration. minute = 35
duration. second = 0
done = add_ time(start,duration)
print_time(done)
Output
Hour: 10
Minute: 80
Second: 30
• The result, 10:80:00 might not be what you were hoping for.
• The problem is that this function does not handle the cases such as the number of seconds
or minutes adds up to more than sixty.
• When that happens, we have to “carry” the extra seconds into the minute column or the
extra minutes into the hour column.
• The next example handles such issues effectively.
Solution to the problem
class Time:
"""Represents the time of day. attributes: hour, minute, second“””
sum.second -= 60
sum.minute += 1
if sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum
def print_time(t):
start = Time()
start.hour = 9
start.minute = 45
start.second = 0
duration = Time()
duration.hour = 1
duration.minute = 35
duration.second = 0
Output
Hour: 11
Minute: 20
Second: 00
2.2.2 Modifiers
• Sometimes it is useful for a function to modify the objects it gets as parameters.
• In that case, the changes are visible to the caller.
Example:
In the below example: increment, which adds a given number of seconds to a Time
object, can be written naturally as a modifier.
def increment(time, seconds):
time.second += seconds
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1
Complete Program
class Time:
time.second += seconds
m = int (time.second/60)
time.hour += h
def print_time(t):
start.hour = 9
start.minute = 45
start.second = 0
seconds = 5000
#print_time(start)
increment(start, seconds)
print_time(start)
Output
Hour: 11
Minute: 20
Second: 00
return seconds
• And here is a function that converts an integer to a Time ( recall that div mod divides
the first argument by the second and returns the quotient and remainder as a tuple).
def int_to_time(seconds):
time = Time()
• Once you are convinced they are correct, you can use them to rewrite add_time:
def add_time(t1, t2):
return int_to_time(seconds)
• Objects often represent things in the real world, and methods often correspond to the ways
things in the real world interact.
• The syntax for invoking a method is different from the syntax for calling a function.
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> print_time(start)
09:45:00
To make print_time a method, all we have to do is move the function definition inside the
class definition.
• Notice the change in indentation.
class Time:
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second))
09:45:00
The second (and more concise) way is to use method syntax:
>>> start.print_time()
09:45:00
3.2 self
Most commonly used python variable
Is a reference variable, which is always pointing to current object.
In python, if you want to access a object we need a reference variable and it is used within
a class.
Self is a reference variable, which is always pointing to current object.
Within a python class, if you want to access current object, you require self-reference
variable.
Example 1:
class Test:
def init (self):
Output:
print(‘x value’,x)
t = Test()
t.m1(10)
Output:
constructor
x value 10
• This constructor will be executed automatically when the object is created. No need to call
the constructor explicitly.
• Constructor will be executed Once per Object.
Example:
class Test:
def init (self):
print(‘constructor execution’)
t1 = Test()
t2 = Test()
t3 = Test()
Example:
class student:
def init (self,name,rollno,marks):
self.marks = marks
s1 = student(‘sunny’,101,90)
print(s1.name,s1.rollno,s1.marks)
Output:
self.addr=addr
obj=Demo('divya','Bengaluru')
print(obj)
output:
self.addr=addr
obj=Demo('divya','Bengaluru')
print(obj.name,obj.addr)
Output:
divya Bengaluru
self.name=name
self.addr=addr
return s
obj=Demo('divya','bengaluru')
Output:
name=divya
Address=Bengaluru
Example:
>>>print(10+20)
>>>print(‘Divya’+’Raj’)
We are using same operator for multiple purposes.
• You might have noticed that the same built-in operator or function shows different
behaviour for objects of different classes, this is called Operator Overloading.
Example :
class Book:
def init (self,pages):
self.pages=pages
b1 = Book(100)
b2 = Book(200)
print(b1+b2)
OUTPUT:
Traceback (most recent call last):
self.pages=pages
total_pages=self.pages+other.pages
return total_pages
b1 = Book(100)
b2 = Book(200)
print(b1+b2)
OUTPUT:
300
Example 2:
class A:
def init (self, a):
self.a = a
ob1 = A(1)
ob2 = A(2)
ob3 = A("Geeks")
ob4 = A("For")
print(ob1 + ob2)
print(ob3 + ob4)
Output:
3
GeeksFor
3.6 Polymorphism
• Very important for day to day coding.
• Poly – Many
• Morphs – Forms
• “one name but many forms”
Example 1: Overriding
class P:
def eat(self):
print(‘idly’)
class C(P):
def eat(self):
print(‘Dosa’)
c=C()
c. eat()
Output:
Dosa
Example 2:
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return 'Woof!'
class Cat(Animal):
def speak(self):
return 'Meow!'
def animal_speak(animal):
print(animal.speak())
dog = Dog('Fido')
cat = Cat('Whiskers')
animal_speak(dog) # prints "Woof!“
Output:
Woof!
Meow!
Explanation:
• In this example, the Animal class serves as a base class for the Dog and Cat classes.
• The speak method is defined in the base class, but overridden in the subclasses to provide
unique behavior.
• The animal_speak function can take any object that is an instance of the Animal class or
any of its subclasses, and it will call the speak method on that object, which will in turn
call the appropriate overridden version of the method.
• Type-based dispatch in Python is a technique used to call different functions based on the
type of the input arguments.
• This can be done using the built-in function "isinstance()" which takes an object and a class
or tuple of classes as arguments, and returns True if the object is an instance of any of the
classes.
return a + b
else:
raise ValueError("Invalid input types")
print(add_numbers(1, 2))
print(add_numbers("hello", "world"))
Output:
3
helloworld
• Type-based dispatch is useful when you want to separate the implementation details of
different types from the main logic of the program.
• It allows you to write more flexible and extensible code by decoupling the type of the
objects from the behavior of the program.
• Inheritance is the capability of one class to derive or inherit the properties from another
class.
• It provides the reusability of a code. We don’t have to write the same code again and again.
Also, it allows us to add more features to a class without modifying it.
Class DerivedClass(BaseClass):
#Body
Example 1:
class Person(object):
# Constructor
def Display(self):
print(self.name, self.id)
# Driver code
Output:
Satyam 102