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

Chapter 3 Object-Oriented Programming in Python

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

Chapter 3 Object-Oriented Programming in Python

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

Chapter 3

Object-Oriented Programming in Python

Thu Huong Nguyen, PhD


Si Thin Nguyen, PhD
About Authors
Thu Huong Nguyen
PhD in Computer Science at Université Côte d’Azur, France
Email: nthuong@vku.udn.vn
Address: Faculty of Computer Science, VKU

Si Thin Nguyen
PhD in Computer Science at Soongsil University, Korea
Email: nsthin@vku.udn.vn
Address: Faculty of Computer Science, VKU
Chapter Content
➢ Class & Object
➢ Attributes
➢ Constructor
➢ Method
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Encapsulation
Class & Object
➢ Object: is the entity/instance with “state” and “behavior”
➢ Features:
- Physical or logic entity
- Having three characteristics: state, behavior, identity
Class & Object
➢ Class:
- Is the template or blueprint from which objects are made
- Can be defined as a collection of object
➢ Including:
- Data: attribute/ field/ instance variable
- Methods
- Constructor
…..
Class & Object
➢ Syntax: Example:
class ClassName: class Employee:
id = 10
#statement_suite name = "Devansh"
def display (self):
print(self.id,self.name)
Attributes
⮚ Concept: The data held by an object is represented by its
attributes
⮚ Types:
- Class variables : defined within the scope of the class, but
outside of any methods
- Instance variables: are tied to the instance (objects) than class
Attributes
⮚Example:
class Person:
# instance_count is class variable
instance_count = 0
def __init__(self, name, age):
Person.instance_count += 1
# name, age are instance variables
self.name = name
self.age = age
Constructor
➢ Concept: is a special type of method (function) which is used to
initialize the instance members of the class.
⮚ Constructors can be of two types.
• Parameterized Constructor
• Non-parameterized Constructor
Constructor
⮚ Syntax: __init__(<parameter>)
➢ Example:
class Employee:
def __init__(self, name, id):
self.id = id
self.name = name

def display(self):
print("ID: %d \nName: %s" % (self.id, self.name))
emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
Method
⮚ Instance method
⮚ Class method
⮚ Static method
⮚ Special method
⮚ Getter, setter method
Instance method
⮚ Concept: it is tied to an instance of the class
⮚ Example:
• “Display(seft)” is a instance method
class Employee: • “self” is used as a reference variable,
id = 0
name = "Devansh" which refers to the current class
def display (self): object. It is always the first argument
print(self.id,self.name)
in the function definition. However,
using self is optional in the function
call
Class method
⮚ Concept: behaviour that is linked to the class rather than an
individual object
⮚ Example:
class Employee: • “increment_id(cls)” is a instance
id = 0
name = "Devansh" method
@classmethod • Is decorated with “@classmethod”
def increment_id(cls):
id+=1 keyword and take a first parameter with
def display (self): “cls”
print(self.id,self.name)
Static method
⮚ Concept: is defined within a class but are not tied to either
the class nor any instance of the class

⮚ Example:
class Employee: • is decorated with the @staticmethod
id = 0 decorator
name = "Devansh"
@staticmethod • the same as free standing functions
def static_function(): but are defined within a class
print(“Static method”)
Special method
⮚ Start and end with a double underbars ('__’).
⮚ You should never name one of your own methods or
functions __<something>__ unless you intend to (re)define
some default behaviour.
⮚ Example: __init__(),
__str__()
__dict__()
__doc__()
__module__()
Getter and setter methods
⮚ Concept: used to access the values of objects
⮚ Getter methods: decorated with the @property decorator
⮚ Setter methods: decorated with the @attribute_name.setter
decorator
Getter and setter methods
⮚ Example:
class Example:
# Attribute
__domain = ''
# Getter
@property
def domain(self):
return self.__domain
# Setter
@domain.setter
def domain(self, domain):
self.__domain = domain
Inheritance
⮚ Concept: the child class acquires the properties and can access all the data members
and functions defined in the parent class
⮚ Note:
• Reuse code
• Method Overriding
▪ Syntax: class derived-class(base class):
<derivedclass-body>
derived/sub class base/super class
Manager Employee
• bonus: double IS- A • name : String
• salary : double
• getSalary() • getSalary()
Inheritance
Single Multi-level inheritance Multiple - inheritance

CLASS A CLASS A CLASS B CLASS C

CLASS B CLASS B CLASS A

CLASS C
Inheritance
⮚ “super()”: is used to call method and constructor of parent class

derived/sub class base/sup class

Manager Employee
IS- A • name : String
• bonus: double
• salary : double

• getSalary() • getSalary()
Polymorphism
⮚ Polymorphism: one task can be performed in different ways
⮚ Note: Runtime polymorphism: Method Overriding

derived/sub class base/sup class

Manager Employee
• bonus: double IS- A • name : String
• salary : double

• getSalary() • getSalary()
Method Overriding
⮚ Concept: subclass (child class) has the same method as declared in the parent
class, it is known as method overriding
⮚ Note: - Same name and the number of parameters
- Runtime polymorphism
- The prefer in the order: left to right, up to down
Abstraction
Concept: main goal is to handle complexity by hiding unnecessary details
from the user
Note:
• We know “what it does” but we don’t know “how it does”
• Abstract Base Classes (ABCs)

Remote Sending Message


Abstract class and abstract method
⮚ Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class)
⮚ Note:
▪ Having at least one abstract method
▪ Can not be instantiated themselves
▪ Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).
⮚ Note:
▪ Is declared in subclass
Abstract Class
⮚ Abstract Base Classes (ABCs) :
- Can be used to define generic (potentially abstract) behaviour that can be
mixed into other Python classes and act as an abstract root of a class
hierarchy.
- There are many built-in ABCs in Python including (but not limited to): IO,
numbers, collection,…modules
⮚ Declared an Abstract Class
- Step 1 :import ABCs, abstract method
- Step 2: Declared an Abstract Class inheritance from ABC class in step 1
- Step 3: Declared Abstract Methods
Abstract Class
▪ Example 1:
from abc import ABC, abstractmethod
class Vidu(ABC):
@abstractmethod
def methodName(self):
pass
▪ Example 2:
from collections import MutableSequence. abstractmethod
class Bag(MutableSequence):
@abstractmethod
def methodName(self):
pass
Interface
▪ Interface: this is a contract between the implementors of an interface and
the user of the implementation guaranteeing that certain facilities will be
provided. Python does not explicitly have the concept of an interface
contract (note here interface refers to the interface between a class and the
code that utilizes that class).
▪ Example: Create an “interface” Shape and subclasses: Circle, Rectangle,
Triangle
Interface
▪ “Interface” Shape
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
@abstractmethod
def perimeter(self):
pass
▪ Circle Class ▪ Rectangle Class
class Circle(Shape): class Rectangle(Shape):
def __init__(self, radius) -> None: def __init__(self, width, height) -> None:
super().__init__() super().__init__()
self.radius=radius self.width=height
def area(self): self.height=height
return 3.14*self.radius*self.radius def area(self):
def perimeter(self): return self.width*self.height
return 2*3.14*self.radius def perimeter(self):
return (self.width+self.height)*2
Encapsulation
⮚ Concept: It is used to restrict access to methods and variables. In encapsulation, code
and data are wrapped together within a single unit from being modified by accident.
⮚ Note:
⮚ Private Attributes
⮚ Using getter and setter methods to access data
class Student: class Student:
def __init__(self, univer): def __init__(self, univer):
self.__univer=univer self.__univer=univer
# getter # setter
@property @univer.setter
def univer(self): def univer(self,univer):
return self.__univer self.__univer=univer
# Missing setter method # Missing getter method
# only read data # Only write data

a= Student(“VKU") a= Student(“VKU")
a.__univer=“VKU University" a.univer=“VKU University"
print(a.univer) print(a.__univer)
# result is not changed: “VKU” # Cannot print

You might also like