lOMoARcPSD|47685040
Notes Module 5 Python Programming
Introduction to python programming (Visvesvaraya Technological University)
Scan to open on Studocu
Studocu is not sponsored or endorsed by any college or university
Downloaded by Vijaykumar H K (
[email protected])
lOMoARcPSD|47685040
MODULE 5
TextBook : Think Python
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,
lOMoARcPSD|47685040
Chapter 15
Classes and objects
15.1 Programmer-defined types
A programmer-defined type is also called a class. A class definition looks like this:
class Point:
"""Represents a point in 2-D space."""
15.2 Attributes
lOMoARcPSD|47685040
Object Diagram
>>> blank.x=4.0
>>> blank.y=5.0
lOMoARcPSD|47685040
15.3 Embedded objects
lOMoARcPSD|47685040
15.6 Copying
lOMoARcPSD|47685040
>>> p1==p2
False
The is operator indicates that p1 and p2 are not the same object.
the default behavior of the == operator is the same as the is operator; it checks object identity, not
object equivalence.
lOMoARcPSD|47685040
isinstance()
Syntax:
isinstance(objectname,classname)
● isinstance() returns True if the specified object name belongs to the class else it returns False.
.
● isinstance() returned True - it indicates p is an instance(object) of class Point.
hasattr()
Syntax:
hasattr(objectname,’attributename’)
lOMoARcPSD|47685040
Chapter 16
Classes and functions
16.1 Pure Functions
lOMoARcPSD|47685040
16.2 Modifiers
lOMoARcPSD|47685040
10
lOMoARcPSD|47685040
11
lOMoARcPSD|47685040
12
lOMoARcPSD|47685040
Chapter 17
Classes and methods
Methods and Functions
13
lOMoARcPSD|47685040
14
lOMoARcPSD|47685040
15
lOMoARcPSD|47685040
17.5 __init__() method
16
lOMoARcPSD|47685040
17.6 __str__() method
17.7 Operator overloading
● By defining other special methods, you can specify the behavior of operators on programmer-
defined types. For example, if you define a method named __add__ for the Time class, you can
use the + operator on Time objects.
● Changing the behavior of an operator so that it works with programmer-defined types is called
operator overloading.
17.8 Type-based dispatch
17
lOMoARcPSD|47685040
Here are examples that use the + operator with different types.
__radd__() method
18
lOMoARcPSD|47685040
17.9 Polymorphism
19