Lecture 03
Lecture 03
Lecture 1
1
Text Books
1. Learning Python
by Mark Lutz
5th editionO’Reilly.
2. Python in a Nutshell
by Alex Martelli, Anna Ravenscroft, and Steve
Third Edition
2
Object-oriented
programming in Python
Introduction
• Object-oriented programming is one such
methodology that has become quite popular
over past few years.
• Python can be characterized under object-oriented
programming methodologies.
What is Object Oriented
Programming?
• Object Oriented means directed towards objects.
• In other words, it means functionally
directed towards modeling objects.
• This is one of the many techniques used for modeling
complex systems by describing a collection of
interacting objects via their data and
behavior.
• Focuses on using objects and classes to design and
build applications.
Why to Choose Object Oriented
Programming?
• Provides a clear program structure, which makes it easy
to map real world problems and their solutions.
• Facilitates easy maintenance and modification of existing
code.
• Enhances program modularity because each object exists
independently and new features can be added easily
without disturbing the existing ones.
• Presents a good framework for code libraries where
supplied components can be easily adapted and modified
by the programmer.
• Imparts code reusability
Principlesof Object Oriented
Programming
• Object Oriented Programming (OOP) is based on
the concept of objects rather than actions, and data
rather than logic.
pillars of object-oriented
programming
Encapsulation
• This property hides unnecessary details and makes
it easier to manage the program structure.
• Each object’s implementation and state are hidden
behind well-defined boundaries and that provides a
clean and simple interface for working with them.
• One way to accomplish this is by making the data
private.
Inheritance
• Inheritance, also called generalization, allows us to
capture a hierarchal relationship between classes
and objects.
• Inheritance is very useful from a code reuse
perspective.
Abstraction
• This property allows us to hide the details and
expose only the essential features of a concept or
object.
• For example, a person driving a scooter knows that
on pressing a horn, sound is emitted, but he has no
idea about how the sound is actually generated on
pressing the horn.
Polymorphism
• Poly-morphism means many forms.
• That is, a thing or action is present in different
forms or ways.
• One good example of polymorphism is constructor
overloading in classes.
Class in python
• In python, classes provide a means of bundling data
and functionality together.
• Creating a new class creates a new type of object
• The class can be defined as a logical grouping of
data and functions
• A class is like a blueprint. Using a blueprint, a
builder can build a house, thus the class is used
create an object.
13
Creating Classes
• The class statement creates a new class definition. The name of the
class immediately follows the keyword class followed by a colon as
follows −
• The statement’s general form:
The line that contains keyword class and the class name is called the class’s
header.
14
Creating Classes
• The class statement creates a new class definition. The name of the
class immediately follows the keyword class followed by a colon as
follows −
• The statement’s general form:
The line that contains keyword class and the class name is called the class’s
header.
15
An example of creating Class
class Person:
name = "Ali" Attributes
age = 22
def info(self):
Method
print(' this is my first class')
16
Object
• The object is a unique instance of a data structure that's
defined by its class.
• Objects (or instance) can store data using ordinary
variables that belong to the object.
• Variables that belong to an object or class are referred to
as attribute or fields.
• Objects can also have functionality by using functions
that belong to a class. Such functions are called methods
of the class.
• The attributes and method are encapsulated into an
object
17
Creating an Object (instances)
• To create an object ( also called instance) , type the
class name, followed by two brackets.
• You can assign this to a variable to keep track of the
object.
• Example:
x = Person() # Person is a class
# x is a new object
18
Example
>>> class Person:
name = "Ali"
age = 22
class
def info(self):
print(' My information')
>>> x = Person() Create an object x
19
Attributes of instance objects
20
Example
>>> class Person:
name = "Ali"
age = 22
class
def info(self):
print(' My information')
def info(self):
print(' My information')
>>> x = Person()
x = Person()
x.My_name('Ali')
My name is Ali
x.info()
Output
•Notice that when we call the My_name method and info methos, we don't have to
supply the self-keyword. That is automatically handled for us by the Python runtime.
•You just have to pass the non-self arguments
24
Constructor (__init__)
• A constructor is a special method that executes
each time an object of a class is created.
• The constructor (method __init__) initializes the
attributes of the object and returns None.
• It can be used to set default values for all
arguments
Note: Returning a value other than None from a constructor is a fatal, runtime
error.
25
Example (1)
class Person:
def __init__(self, my_name):
self.name = my_name
def info(self):
print('My name is', self.name)
p = Person('Ali')
p.info()
Output
26
Example (2)
class Person:
def __init__(self, name):
self.name = name
print('My name is', self.name)
p = Person('Ali')
My name is Ali
Output
* Can you create the above object without passing any argument? Why?
27
The __doc__ attribute
28
Example of __doc__ attribute
class Person:
"""This is a Person Class
This class provides ..."""
def My_name(self, name):
self.name = name
def info(self):
print('My name is', self.name)
Output
29
Destructors
• A destructor executes when an object is destroyed
(e.g., after no more references to the object exist).
• A class can define a special method called __del__
that executes when the last reference to an object
is deleted or goes out of scope.
• The method itself does not actually destroy the
object—it performs termination housekeeping
before the interpreter reclaims the object’s
memory, so that memory may be reused.
• A destructor normally specifies no parameters
other than self and returns None.
30
Example
class Person:
def __init__(self):
print(‘My information')
def __del__(self):
print('Destructor called, Person deleted.')
>>> p = Person()
31
Variables in Class
When dealing with OOP, there are three types of
variables you should be aware of:
1) Local variable
2) Instance attribute
3) Class attribute
32
More about Class variables – Cont’d
1) local variable: These are the variables that used inside class
functions/methods — once the function/method is done being
called, this variable is no longer able to be accessed.
class Person:
def __init__(self, the_name): Local Variable
self.name = the_name
def info(self):
print('My name is', self.name )
>>> p1 = Person('Ali')
class Person:
def __init__(self, name): e
self.name = name
>>> p1 = Person('Ali')
>>> print (p1.name)
Ali
>>> p2 = Person('Ahmed')
>>> print (p2.name)
Ahmed
34
More about Class variables – Cont’d
p1 = Person('Ali')
print('name : ',p1.name,' ID : ',p1.id)
p2 = Person('Ahmed')
print('name : ',p2.name,' ID : ',p2.id)
What is the value of Person.id after creating the second object p2? Why?
Change the Person.id in __init__ method to self.id, see the result.
Why? 35
Built in Functions for classes
getattr()
setattr()
delattr()
36
Built in Functions : getattr()
The getattr() function returns the value of the
specified attribute from the specified object.
Syntax:
getattr(object, attribute, default)
Parameter Description
object Required. An object.
attribute The name of the attribute you want to get the value from
default Optional. The value to return if the attribute does not exist
37
Example of getattr()
Get the value of the "age" property of the "Person"
object:
class Person: class Person:
name = "Ali" name = "Ali"
age = 36
x=getattr(Person, 'age',
x = getattr(Person, 'age') 'my_message')
38
Built in Functions : setattr()
• The setattr() function sets the value of the specified
attribute of the specified object.
• If the attribute is not found, setattr() creates a new
attribute by the given name and value.
Syntax
setattr(object, attribute, value)
Parameter Description
object Required. An object.
attribute Required. The name of the attribute you want to set
value Required. The value you want to give the specified attribute
39
Example of setattr()
To set the value of the "age" property of the "Person" object:
class Person:
name = "Ali"
age = 36
country = "A"
setattr(Person, 'age', 40)
40
Built in Functions : delattr()
The delattr() function will delete the specified
attribute from the specified object.
Syntax
delattr(object, attribute)
Parameter Description
object Required. An object.
attribute Required. The name of the attribute you want to remove
41
Example of : delattr()
Delete the "age" property from the "person":
class Person:
name = "Ali"
age = 36
delattr(Person, 'age')
Notice: You can use dir() function to show all properties and methods of the
specified object.
>>> print (dir(Person))
Notice: You can delete properties on objects by using the del keyword
>>> del Person.age # to remove ‘age’ property
42
Private and public in Python
• All member variables and methods are public by
default in Python.
• “Private” instance variables that cannot be accessed
except from inside an object don’t exist in Python.
However, there is a convention that is followed by most
Python code: prefix the name of the attribute with two
underscore characters (__), (ex: __age).
• Python creates an attribute called
_className__attName, instead of an attribute called
__attName, where classname is the current class name.
• This technique called name mangling.
43
Private Attributes - Example
In the example below, the Python creates an attribute called _Person__age,
instead of an attribute called __age
class Person:
name = "Ali"
__age = 36
def info(self)
print(self.name)
>>> print(Person.name)
Ali
>>> print(Person._Person__age)
36
44
Exercises
Write a class with tow integer numbers and with the
following methods:
a) Constructor to initialize the above numbers
b) Add to print their sumExercises
45
Exercises
• Write a class with one integer and with the
following methods:
a) Constructor to initialize this number
b) Method to read the value of this number from
the user.
c) Method to check its even or odd.
d) Method to print its factorial
e) Method to print its divisor greater than one.
46