0% found this document useful (0 votes)
35 views

Lecture 03

The document discusses object-oriented programming in Python, explaining that it focuses on using classes and objects to design applications by bundling data and functionality together. It describes some key principles of object-oriented programming like encapsulation, inheritance, polymorphism and abstraction. The document also provides an example of how to define a class in Python and create objects from the class.

Uploaded by

ج 90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

Lecture 03

The document discusses object-oriented programming in Python, explaining that it focuses on using classes and objects to design applications by bundling data and functionality together. It describes some key principles of object-oriented programming like encapsulation, inheritance, polymorphism and abstraction. The document also provides an example of how to define a class in Python and create objects from the class.

Uploaded by

ج 90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Object-Oriented Programming

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:

class ClassName: # Assign to name


attr = value # Shared class data
def MethodName(self,...): # Methods
self.attr = value # Per-instance data

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:

class ClassName: # Assign to name


attr = value # Shared class data
def MethodName(self,...): # Methods
self.attr = value # Per-instance data

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

* The attributes and method are encapsulated into object x


* How we can access to its data and methods?

19
Attributes of instance objects

• Once you have created an instance, you can access


its attributes (data and methods) using the dot (.)
operator.

20
Example
>>> class Person:
name = "Ali"
age = 22

class
def info(self):
print(' My information')

>>> x = Person() Create an object x

>>> x.name = “Ahmed” To set a value to an attribute

>>> print(x.name) To print a value of an attribute

>>> x.info() To call the method info()


21
Example
>>> class Person:
name = "Ali"
age = 22
class

def info(self):
print(' My information')
>>> x = Person()

>>> x.name = “Ahmed” My information


>>> x.info()
The output after
calling x.info() 22

• A class serves as a template for its objects (instances)


The Self
• Class methods have only one specific difference from
ordinary functions - they must have an extra first name that
has to be added to the beginning of the parameter list.
• There is No value for this parameter when the method is
called, Python will provide it.
• This particular variable refers to the object itself, and by
convention, it is given the name self.
• Although, you can give any name for this parameter, it is
strongly recommended that you use the name self - any
other name is definitely frowned upon.
• There are many advantages to using a standard name - any
reader of your program will immediately recognize it.
23
Example
class Person:
def My_name(self, name):
self.name = name
The Class
def info(self):
print('My name is', self.name)

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()

# The previous 2 lines can also be written as


# Person(‘Ali').info()
My name is Ali

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

Note : the method __init__ executes each time an object is created

* Can you create the above object without passing any argument? Why?

27
The __doc__ attribute

• Each Python object (functions, classes,...) provides


(if programmer has filled it) a short documentation
which describes its features.
• You can access it with commands like print
myobject.__doc__.
• You can provide a documentation for your own
objects (functions for example) in the body of their
definition as a string surrounded by three double-
quotes

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)

p = Person() This is a Person Class


print(p.__doc__) This class provides ...

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()

>>> del p To called the destructor

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.

In the example below, the the_name variable in the __init__ method


is a local variable (not the self.name variable).

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')

Can you access to the_name variable from outside the method?


Why?
33
More about Class variables – Cont’d

2) instance attribute: Unlike local variables, instance attributes will still


be accessible after method calls have finished. Each instance of a class
keeps its own version of the instance attribute.
In the example below, we can defined two Person objects (p1 and p2),
where one's self.name is ‘Ali’, and the other's self.name is ‘Ahmed’.

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

3) class attribute: As with instance attributes, class attributes also


persist across method calls. However, unlike instance attributes, all
instances of a class will share the same class attributes.
In the example below, the class attribute (id) in Person class share
its value with p1 and p2
class Person: The output:
id = 0
name : Ali ID : 1
def __init__(self,name):
self.name= name
name : Ahmed ID : 2
Person.id= Person.id + 1

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')

the value of x is equal to 36 The value of x will be ‘my_message’

The above syntax is equivalent to: Why?


x = Person.age

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)

The above syntax is equivalent to:


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

 Try to access to the attribute __age by using (Person.__age)


 How about prefixing the method info with two underscores? Try that.

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

c) Sub to print their subtract


d) Mul to print their multiplication
e) Div to print their division
f) Test the class in the main

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

You might also like