Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
1 views

Module 5 Python Final

Uploaded by

ghthanushkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Module 5 Python Final

Uploaded by

ghthanushkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Module -5

Classes and Objects

By
Naveen Kumar .V
Programmer-defined types

Many Python’s built-in types :- string, list , tuple etc

Define a new user defined type


Eg :- Point (2D space)

Point (0, 0) represents the origin


Point (x, y) represents the point x units to the right
y units up from the origin.

Several ways we might represent points in Python:


1. We could store the coordinates
 separately in two variables, x and y.
 as elements in a list or tuple.

2. We could create a new type to represent points as objects.


Programmer-defined types -Class

A programmer-defined type is also called a class.

Class :-It the blueprint or template that specifies what data and
functions should be included in the objects.

.
Object :- An object is an identifiable real world entity with
some characteristics and behaviour.
Example :- Class point

Creating a new class is called Point

The body is a docstring that explains what the class is used for.
Object Creation :- instantiation

To create an object also called an instance of Point(class)


 you call Point as if it were a function.

The return value is a reference to a Point object, which we assigned to


blank.

The process of creating a new object :- instantiation.


instance of the class :- object created
Attributes

One can assign values to an instance using dot notation.

Created two elements of an object and assigned values to them.

Object diagram of point


object (instance) + its associated attributes :- object diagram

The variable blank refers to a object point, which contains two attributes.
Each attribute refers to a floating-point number.
Point Object

The value of an element of an object can be displayed as shown below.

Two syntaxes are shown with and without using a format specifiers.

Syntax -1
print ('The value of element x is: ‘, blank.x)
print ('The value of element y is: ‘, blank.y)

Output
The value of element x is: 3.0
The value of element y is: 4.0
Syntax -2
print('The value of element x is %g \n The value of element y is %g' %
(blank.x, blank.y))

Output:
The value of element x is 3
The value of element y is 4

%g :- flexible way to represent numbers


either fixed-point/exponential notation based on value
Rectangles

Attributes of an object Either


1. Obvious (corner ,width , height )
2. make decisions(opposite corners )

Eg:- Design a class to represent rectangles

There are at least two possibilities:


 Specify one corner of the rectangle (or the center) using point, the width, and the height.
 You can specify two-point to represent opposite corners.

Corner is a Point object :- specifies the lower-left corner.


⮚ To represent a rectangle,
Instantiate a Rectangle object and assign values to the attributes:
An object that is an attribute of another
object is embedded .

The expression box.corner.x


“Go to object box  select attribute cornerthen go to
object point and select the attribute named x.”
Instances as return values

Functions can return instances


Eg:- find_center takes a Rectangle as argument
returns a Point that contains the coordinates of the center of the
Rectangle:

Example:- passes box as argument and assigns the resulting Point to center
Objects are mutable

We can change the state of an object by making an assignment to


one of its attributes

Eg:- To change the size of a rectangle without changing its position

By modifying the values of width and height


We can also write functions that modify objects.

Eg: - grow_rectangle()
Takes a Rectangle object and two numbers, dwidth & dheight
Adds the numbers to the width and height of the rectangle
Copying

Aliasing can make a program difficult to read


 Changes in 1 place might have unexpected effects in another place
 Hard to keep track of all the variables

• Copying an object :- alternative to aliasing.

copy module:- Contains copy function that can duplicate any object
shallow copy

If you use copy.copy to duplicate a Rectangle


copies the Rectangle object but not the embedded Point.

shallow copy
it copies the object and any references it contains, but not the
embedded objects.
deepcopy

Available in copy module


deepcopy
copies not only the object but also the objects it refers to,
and the objects they refer to, and so on.
Time

As another example of a programmer-defined type:- class Time


It records the time of day.
Pure functions

pure function : -Does not modify any of the objects passed as arguments

And it has no effect, like displaying a value/getting user input,


other than returning a value.

The function creates a new Time object


 initializes its attributes
 returns a reference to the new object.

Creating two Time objects


start :- contains the start time of a movie
duration:- contains the run time of the movie
(which is one hour 35 minutes)
add_time:- figures out when the movie will be done.
There is a problem with this function:- It does not deal with cases
where 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.

Here’s an improved version:


Modifiers

Modifiers :- functions used to modify the objects it gets as parameters.

Eg:- increment ( ) which adds a given number of seconds to a Time object,


can be written naturally as a modifier.
Anything that can be done with modifiers
can also be done with pure functions.

In fact, some programming languages only


allow pure functions.

• Programs that use pure functions are faster


develop and less error-prone

But modifiers are convenient at times,


functional programs(pure) tend to be less
efficient.
There is a problem with this function:- It does not deal with cases
where the number of seconds or minutes adds up to more than sixty.

Here’s an improved version for modifiers:


Prototyping versus planning

Prototype Method :- writing a rough draft of a program, testing, and


correcting errors as they are found.
 It is a Creational Design Pattern where object is created by copying a
prototypical instance during run-time.
 Aims to reduce the number of classes used for an application.
 It allows us to copy existing objects then modify it according to our
needs.
 Here the Best when the object creation is an expensive.
( time and usage of resources)
.
Designed development: A development plan that involves
high-level insight into the problem and more planning
than incremental development or prototype development.
It can make the programming much easier.

In this case, the insight is that a Time object is really a three digit
number in base 60.

• second attribute is :- “ones column”,


minute attribute is :- “sixties column”,
hour attribute is :- “thirty-six hundreds column”.
Here is a function that converts Times to integers:
Prototyping versus planning
Classes and methods

Object-oriented features
 Programs include class and method definitions.
 Most computation expressed :- As operations on objects.
 Objects often represent things in the real world
 methods often corresponds to ways things in the real world interact.

 A method is a function that is associated with a particular class.


• 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.
Printing objects

Function named print_time is written as follows:


To make print_time a method, all we have to do is
move the function definition inside the class definition.
Also notice the change in indentation.

Now there are two ways to call print_time.


Method 1

The subject of a method invocation is what the method is about.


Inside the method, the subject is assigned to the first parameter, so in this case start
is assigned to time.
Method 2

Inside the method, the subject is assigned to the first parameter, so


in this case start is assigned to time.
By convention, the first parameter of a method is called self, so it
would be more common to write print_time like this:

The reason for this convention is an implicit metaphor:

• The syntax for a function call, print_time(start),


suggests that the function is the active agent.
It says something like, “Hey print_time! Here’s an object for you to print.”

In OOPs, the objects are the active agents


A method invocation like
start.print_time() says “Hey start! Please print yourself.”
Here’s a version of increment rewritten as a method:

This version assumes that time_to_int ( ) is written as a method.


Also, note that it is a pure function, not a modifier.
Here’s to invoke increment( ):
The init method

The init method (short for “initialization”) is a special method that gets
invoked when an object is instantiated.
Its full name is _ _init_ _.
An init method for the Time class might look like this:

It is common for the


parameters of _ _init_ _ to have the same names as the attributes.

self.hour = hour stores the value of the parameter hour as an attribute of self.

The parameters are optional


if you call Time with no arguments, you get the default values.
The str method

_ _str_ _ is a special method, like _ _init_ _, that is supposed to


return a string representation of an object.
It is automatically called when a reference to an object is passed to
print() function.
Eg:- here is a str method for Time objects:
Operator overloading

By defining other special methods, we can specify the behaviour of


operators on programmer defined types.

Eg:- if you define a method named _ _add_ _ for the Time class,
you can use the + operator on Time objects.

Add invoked

Str invoked
When applying + operator to Time objects  python invokes _ _add_ _.
When you print the result  Python invokes _ _str_ _.

Changing the behaviour of an operator so that it works with programmer


defined types is called operator overloading.

For every operator in Python


There is a corresponding special method, like add .
Type-based dispatch

Adding two Time objects with an integer to a Time object.


The built-in function isinstance() takes a value and a class object,
and returns True if the value is an instance of the class.

• If other is a Time object, _ _add_ _ invokes add_time ( )


Otherwise it assumes its a number and invokes increment( )

This operation is called a type-based dispatch because it


Dispatches the computation to different methods
 based on the type of the arguments.
Unfortunately, this implementation of addition is not commutative.
If the integer is the first operand, you get
>>> print(1337 + start)

TypeError: unsupported operand type(s) for +: 'int' and 'instance'


• The problem is, instead of asking the Time object to add an integer
Python is asking an integer to add a Time object, and it doesn’t
know how.
• But there is a clever solution for this problem:

the special method _ _radd_ _, which stands for “right-side add”.


This method is invoked when a Time object appears on the right side of
the + operator.

Here’s the definition:


Polymorphism

Functions that work with several types are called polymorphic.


Polymorphism can facilitate code reuse.

Eg:- the built-in function sum ( ) , which adds the elements of a sequence,
works as long as the elements of the sequence support addition.
Since Time objects provide internally an _add_ method, they work with
sum ( ) :

In general, if all of the operations inside a function


work with a given type, the function works with that
type.

The sum () internally calls _add_( ) method multiple


times on the list to get the appropriate result.
Interface and implementation

One of the goals of object-oriented design :- software more maintainable


keep the program working when other parts of the system
change, and modify the program to meet new requirements.

• Design principle :- keep interfaces separate from implementations.

For objects, that means that the

methods a class provides :- should not depend on how the attributes are
represented.
Eg:- class that represents a time of day.
Methods provided by this class include:- time_to_int() ,
is_after() , add_time () .
We could implement those methods in several ways.

Details of the implementation depend on how we represent time.


The attributes of a Time object :- hour, minute, and second.
An alternative

Replace these attributes with a single integer representing the number


of seconds since midnight.
This implementation would make some methods, like is_after ( ), easier
to write, but it makes other methods harder.

After deploying new class, you might discover a better implementation.


If other parts of the program are using our class,
 it might be time-consuming and error-prone to change the
interface.

• If we designed the interface carefully, you can change the


implementation without changing the interface,
THE END

You might also like