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

Module 5 Python

The document covers key concepts of object-oriented programming, including classes, objects, attributes, and methods. It explains copying methods (shallow and deep copy), pure functions, modifiers, operator overloading, polymorphism, and the significance of the __init__ and __str__ methods. Additionally, it discusses type-based dispatch, instances as return values, and the representation of rectangles in programming.

Uploaded by

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

Module 5 Python

The document covers key concepts of object-oriented programming, including classes, objects, attributes, and methods. It explains copying methods (shallow and deep copy), pure functions, modifiers, operator overloading, polymorphism, and the significance of the __init__ and __str__ methods. Additionally, it discusses type-based dispatch, instances as return values, and the representation of rectangles in programming.

Uploaded by

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

Module-5

Classes and objects: Programmer-defined types(class), Attributes, Rectangles,


Instances as return values, Objects are mutable, Copying(shallow copy and deep
copy),
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.

8)What is class,object,attributes

Class:
A programmer-defined type is also called a class.

Example:

class enc :
"""studying plc subject."""

Objects

An object is called an instance of a class.

Example, suppose ENC is a class then we can create objects like diva, divb from
the class.

Here's the syntax to create an object.

objectName = ClassName()

diva =enc()
divb =enc()

Creating a new object is called instantiation, and the object is an instance of the
class
Attributes
The variables inside a class are called attributes. We use the . dot notation to access
the attributes of a class.

Class point:
x=0
y=0

blank=point()

blank.x=3.0

blank.y=4.0

print(blank.x, blank.y)

Explain Copying (shallowcopy() and deep copy() with an example.

Copying
The copy module contains a function called copy that can
duplicate any object.

p1 and p2 contain the same data, but they are not the same
Point:
The is operator indicates that p1 and p2 are not the same object.

Shallow copy: It is used to copy the contents of an object,


including any references to embedded objects, and implemented
by copy module.

embedded object: An object that is stored as an attribute of


another object .
Deepcopy()
It copies not only the object but also the objects it refers to, and
the objects they refer to, and so on. Implemented by deepcopy()
method.

box3=copy.deepcopy(box)

box3 is box
False

box3.corner is box.corner
False

9)Demonstrate pure functions and modifiers with examples.

A function that does not modify any of the objects it receives as arguments. Most
pure functions are frutitful.

A function is not pure if there is something outside the function that can change its
return, given the same arguments.

Example:

Pure function

def add(a, b):


return a + b
res=add(1, 2)
print(res)
OR
Example :2 pure function

11 20 3011 20 30

11:20:30
Modifiers
A function to modify the objects it gets as parameters.

In that case, the changes are visible to the caller. These Functions are called
modifiers.

increment() function adds a given number of seconds to a Time object which is


visible to the called function.

Here adding seconds

Sec=65

start = Time() 60+5 one min added


start.hour = 9
start.minute = 45
start.second = 0
seconds = 65
increment(start, 65) Output:
print_time(start)

9:46:5
10)Explain Operator overloading and polymorphism

Changing the behavior of an operator so that it works with programmer-defined


types is called operator overloading.

It is the ability of a function or an operator to behave in different ways based on the


parameters that are passed to the function.

Example:-1 Example-2

class Point:

def __init__(self, x):

self.x = x

def __add__(self, other):

x = self.x + other.x

return self.x + other.x

p1 = Point(1)

p2 = Point(2)

print(p1+p2)

p3=Point("hi")

p4=Point(“enc")

print(p3+p4)
Polymorphism

Polymorphism refers to having multiple forms.

It is a programming term that refers to the use of the same function name, but
with different signatures, for multiple types

Functions that work with several types are called polymorphic. Polymorphism can
facilitate code reuse

This function also works for lists, tuples, and even dictionaries.

Example: Program to demonstrate polymorphism


with function to find histogram to count
def histogram(st):
the numbers of times each letters appears
d = dict()
for c in s: in a word.
if c not in d: Output:
d[c] = 1 word and value are
else: phy 3
d[c] = d[c]+1 maths 1
return d plc 2
st = ['phy', 'maths', 'plc', 'plc', 'phy', 'phy']
dic=histogram(st)
11) Explain The init method and The __str__ with an example.
The init method (short for “initialization”) is a special method that gets invoked
when an object is instantiated.

Its full name is __init__ (two underscore characters, followed by init, and then two
more underscores)

It is common for the parameters of __init__ to have the same names as the
attributes. The statement self.hour = hour

 stores the value of the parameter name as an attribute of self.


 The parameters are optional, so if we call method with no arguments, we
get the default values
 If we provide one argument, it overrides one argument , If we provide two
arguments, they override two arguments

class Time:
""" represents time in hour,min,sec"""
def __init__(self,hour=0,min=0,sec=0):
self.hour=hour
self.min=min
self.sec=sec

def print_time(time):
print(time.hour,time.min,time.sec)

t=Time()
t.print_time()
0:0:0

x=Time(9)
x.print_time() 9:0:0
y=Time(9,30,45)
y.print_time() 9:30:45
The__str__Method

This method returns the string representation of the object. This method is
called when print() or str() function is invoked on an object.

This method must return the String object.

Example:

#inside the class Time:

def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.min, self.sec)

t=Time(7) 07:00:00
print(t)

tt=Time(7,56,9) 07:56:09
print(tt)

12) Explain Type-based dispatch

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 that


the parameter is 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.

# inside class Time:


def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
def add_time(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)

def increment(self, seconds):


seconds += self.time_to_int()
return int_to_time(seconds)

Here we use the + operator with different types:

>>> start = Time(9, 45)


>>> duration = Time(1, 35)
>>> print(start + duration)
11:20:00

>>> print(start + 1337)


10:07:17

13) Explain Instances as return values and Rectangles

Functions can return instances. find_center takes a Rectangle as an argument and


returns a Point that contains the coordinates of the center of the Rectangle:

Here we are passing box as an argument and assigns the resulting Point to center
Rectangles
We can ignore the angle and assume that the rectangle is either vertical or
horizontal.

There are two possibilities:


 We could specify one corner of the rectangle the width, and the height.
 We could specify two opposing corners

class Rectangle :
"""Represents a rectangle.
attributes: width, height, corner.
"""

To represent a rectangle,

We have to instantiate a Rectangle object and assign values to the attributes:

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 the attribute named corner; then go to
that object and select the attribute named x
Printing Objects
we defined a class named Time and in Time we
wrote a function named print_time.

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


argument:

There are two ways to call print_time.

The first way is to use function syntax:

The second (and more concise) way is to use method syntax:


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.

Differences between Methods and functions:

 Methods are defined inside a class definition .


 The syntax for invoking a method is different from the syntax for calling a
function

Time

It is another example of a programmer-defined type, Time is a class that


records the time of day.

The class definition looks like this:


Objects are mutable

We 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, we
can modify the values of width and height:

box.width = box.width + 50
box.height = box.height + 100

We can also write functions that modify objects.

grow_rectangle takes a Rectangle object rect 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

Output:
>>> box.width, box.height
(150.0, 300.0)
>>> grow_rectangle(box, 50, 100)

>>> box.width, box.height


(200.0, 400.0)

You might also like