Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

4.1 Classes and Objects 4.3 Classes and Methods

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 64

Module4

4.1 Classes and objects


4.2 Classes and functions
4.3 Classes and methods
4.1 Classes and Objects
What are classes and objects
in Python?
• Python is an object oriented programming language.
• Class is a abstract data type which can be defined as
a template or blueprint that describes the behavior /
state that the object of its type support.
• An object is an instance of class . Objects have states
and behaviors. Example: A dog has states - color,
name, breed as well as behaviors – wagging the tail,
barking, eating
• Object is simply a collection of data (variables)
and methods (functions) that act on those data.
• The process of creating this object is
called instantiation
Defining a Class in Python
• We define a class using the keyword class.
• The first string is called docstring and has a
brief description about the class. Although not
mandatory, this is recommended.
• A class attributes are data members(
variables) and functions.
Syntax
The class statement creates a new class definition.
The name of the class immediately follows the
keyword class followed by a colon as follows −

class ClassName:
“””Optional class documentation string' class_suite”””
class_suite

• The class has a documentation string, which can be accessed via


ClassName.__doc__.
• The class_suite consists of all the component statements defining
class members, data attributes and functions.
Example

The header indicates that the new class is called Point.


The body is a docstring that explains what the class is for. You can define variables and
methods inside a class definition.
Creating an Object in Python
• Class can be used to create new object
instances (instantiation) of that class.
• The procedure to create an object is similar
to a function call.
• Example : blank = Point()

The return value is a reference to a Point object, which we assign to blank.


Example1
Example 2
• The variable empCount is a class variable whose value
is shared among all instances of a this class. This can
be accessed as Employee.empCount from inside the
class or outside the class.
• The first method __init__() is a special method, which
is called class constructor or initialization method
that Python calls when you create a new instance of
this class.
• We can declare other class methods like normal
functions with the exception that the first argument
to each method is self.
• Python adds the self argument to the list for you; you
do not need to include it when you call the methods.
Creating Instance Objects
• To create instances of a class, you call the class
using class name and pass in whatever
arguments its __init__ method accepts

emp1 = Employee(“Raju", 2000)


emp2 = Employee(“Swamy", 5000)
Accessing Attributes
• We can access the object's attributes using
the dot operator with object.
• Class variable would be accessed using
class name as follows −
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
Example2 : Rectangle
• Rectangle can be created using following two
possibilities:
– You could specify one corner of the rectangle
(or the center), the width, and the height.
– You could specify two opposing corners.
Instances as return values

• Functions can return instances.


• For example, find_center takes
a Rectangle as an argument and
returns a Point that contains the
coordinates of the center of the
Rectangle:
Objects are mutable

• You can change the state of an object by


making an assignment to one of its attributes.
For example, to change the size of a
rectangle without changing its position, you
can modify the values of width and height:
• box.width = box.width + 50
• box.height = box.height + 100
Modifying through functions
• You can also write functions that
modify objects.
• For example, grow_rectangle takes a
Rectangle object and two numbers, dwidth
and dheight, and adds the numbers to the
width and height of the rectangle:
def grow_rectangle(rect, dwidth, dheight):
rect.width += dwidth
rect.height += dheight
Copying
• Copying an object is often an alternative to
aliasing. The copy module contains a function
called copy that can duplicate any object:
Module4

4.1 Classes and objects


4.2 Classes and functions
4.3 Classes and methods
4.1 Classes and Functions
4.1 Classes and Functions
• Functions are User Defined Functions
• Consider a Definition of Class
class Time :
pass
• New Objects of Class the class can be
created time = Time()
time.hours = 11
time.minute = 59
time.search = 30
• User defined Function to display the attribute of object say ob.
def printTime(ob)
print(“Hours :” Ob.Hours , ”minute:” Ob.minute, “seconds:” ob.seconds)
4.1.1Two Kinds of Functions

1. Pure Functions
2. Modifiers
4.1.1.1. Pure Function

• The function which creates new object ,


initiates its attributes and returns a reference
to the new object is called a pure function.
• It is called pure function because it does not
modify any of the objects passed to it as
arguments of the objects passed to it as
arguments and it has no side effects, such
as displaying value or getting user input.
Example
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second

if sum.second >= 60:


sum.second -= 60
sum.minute += 1
if sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum
Usage of add_time(t1,t2)
>>> start = Time() >>> duration = Time()
>>> start.hour = 9 >>> duration.hour = 1
>>> start.minute = 45 >>> duration.minute = 35
>>> start.second = 0 >>> duration.second = 0

> done = add_time(start, duration)


> print_time(done)
11:20:00
4.1.1.2.Modifiers

• The functions which are used to modify one


or more of the objects its gets as arguments
are called modifiers. Most modifiers are
fruitful.
Example
def increment(time, seconds):
time.second += seconds

if time.second >= 60:


time.second -= 60
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1
4.1.2 Prototype and
Planned Development

• Prototype Development
• Planned Development
Prototype Development

• Prototype involves
– Writing a Rough draft of programs ( or prototype)
– Performing a basic calculation
– Testing on a few cases , correcting flaws as
we found them.
• Prototype development leads
code complicated
Planned Development

• High level insight into the problem can


make the programming much easier
• Example : A time object is really a three digit
number in base 60. The second component is
the “Ones Column” the minute component is
the “sixties column” and the hour component
is the thirty six hundred column.
Example

def convertToSeconds(t):
minutes = t.hours*60 + t.minutes
seconds = minutes *60 +
t.seconds return seconds
Example 2

def makeTime(seconds ):
time = Time()
time.hours = seconds//3600
time.minute = (seconds%3600)//60
time.seconds = seconds%60
return time
Example

def addTime(t1,t2):
seconds = convertToseconds(t1) + convertToseconds(t2)
return makeTime(seconds)
Module4

4.1 Classes and objects


4.2 Classes and functions
4.3 Classes and methods
4.2 Classes and Methods
4.2.1 Object Oriented Features

• Python is an object-oriented programming


language, which means that it provides
features that support object-oriented programming,
which has these defining characteristics:
– Programs include class and method definitions.
– Most of the computation is expressed in terms of
operations on objects.
– Objects often represent things in the real world, and
methods often correspond to the ways things in the
real world interact
Printing objects

class Time:
"""Represents the time of day."""

def printTime(time):
print str(time.hours) + “:” str(time.minutes) “:” + str(time.seconds)

To call this function, you have to pass a Time object


as an argument:
To call this function, you have to pass a
Time object as an argument:

> currentTime = Time()


> currentTime.hour = 9
> currentTime.minute = 45
> currentTime.second = 00
> printTime(currentTime)
09:45:00
4.2.2 Methods versus Functions

• Methods are just like functions with


two differences :
– Methods are defined inside a class definition in
order to make the relationship between the class
and the method explicit
– The syntax for invoking a method is different
from the syntax for calling a function.
4.2.3Transforming functions
into methods

• The function definition must be done within the


class definition
Example1

class Time:
def print_time(time):
print str(time.hours) + “:” str(time.minutes) “:” + str(time.seconds)
Example2
Class Time :
# previous method definition
here def increment(self,seconds):
self.seconds = seconds+ self.seconds
while self.seconds>=60:
self.seconds = self.seconds -60
self.minutes = self.minutes +1
while self.minute>=60:
self.minutes >=60 :
self.hours = self.hours +1
Invoking increment as a
method

>>> currentTime.increment(500)
4.2.4 Optional Arguments

• In python we can write user defined


functions with optional argument lists.
Example

def find(str, ch, start =0):


index = start
while index <less(str):
if str[index] == ch:
return index
index = index +1
return -1
Note

• The third parameter start is optional


because a default value 0 is provided.
• If we invoke find with only two argument
it uses the default value and start from the
beginning of the string:
Example

• find(“apple”, “p”) 1

• find(“apple”, “p”,2) 2

• find(“apple”, “p”,3) 1
4.2.5 Initialization method

• The initialization method is a special method


that is invoked when an object is created.
• The name of this method is : __init__ (two
underscore characters followed by init and
then two more underscore)
Example

• # inside class Time:


def __init__(self, hours=0, minutes=0, seconds=0):
self.hours = hours
self.minutes = minutes
self.seconds = seconds
Invoking a method

currentTime = Time(9,14,30)
currenTime.print_time() -> 9:14:30

currentTime = Time()
currenTime.print_time() -> 0:0:0

currentTime = Time(9)
currenTime.print_time() -> 9:0:0
Invoking a method

currentTime = Time(9,14)
currenTime.print_time() -> 9:14:0

currentTime = Time(seconds = 30,hours


=9) currenTime.print_time() -> 9:0:30
4.2.6 Method Overriding

class Point :
def __init__(self,x=0,y=0):
self.x = x
self.y = y
def __str__(self):
return ‘(‘+str(self.x)+’,’+str(self.y)+’)
Method Overriding

• If a class provides a method __str__ it


overrides the default behavior of the
Python built in str function
• P = Point(3,4)
• str(P)
• ‘(3,4)’
4.2.7 Operator Overloading

• Operator overloading is one of the feature of


OOP language which make possible to change
the definition of the build in operators when
they are applied to user defined type.
• It is especially useful when defining new
mathematical types.
Example
class Point:
def __add__(self,other):
return Point(self.x + other.x, self.y + other.y)

P1 = Point (3,4)
P2 = Point(5,7)
P3 = P1 + P2

Print(P3) (8,11)
4.2.8 Polymorphism

• A polymorphic function can operate on more


than one type . If all the operations in a
function can be applied to a type , then the
entire function can also be applied to a type.
Example

def multadd(x, y, z)
return x*y + z
Invoking multadd()

• multadd(3,2,1) -> 7
• P1 = Point(3,4)
• P2 = Point(5,7)
• print multadd(2,P1,P2) -> (11,15)
• Print multadd(P1,P2,1) -> 44
A function like this that can take arguments
with different types is called polymorphic.
End of Module 4

https://proftgs.blogspot.in/

You might also like