Chapter 0003
Chapter 0003
• Introduction to OOP
• self keyword
• super keyword
• Polymorphism
• Access specifiers
Advanced Python
Introduction to OOP
Introduction to OOP
● An object is a software entity that contains both data and procedures. The data contained in
an object is known as the object’s data attributes. An object’s data attributes are simply
variables that reference data.
● The actions that an object performs are known as methods. An object’s methods are
functions that perform operations on the object’s data attributes.
● The object is, conceptually, a self-contained unit that consists of data attributes and methods
that operate on the data attributes.
Advanced Python
● OOP addresses the problem of code and data separation through encapsulation and data hiding.
● Encapsulation refers to the combining of data and code into a single object.
● Data hiding refers to an object’s ability to hide its data attributes from code that is outside the object
● Only the object’s methods may directly access and make changes to the object’s data attributes.
● An object typically hides its data, but allows outside code to access its methods.
Advanced Python
● When an object's internal data is hidden from outside code and access to that data is
restricted to the object’s methods, the data is protected from accidental corruption.
● In addition, the programming code outside the object does not need to know about the
format or internal structure of the object’s data.
Advanced Python
● In addition to solving the problems of code and data separation, the use of OOP has also
been encouraged by the trend of object reusability.
● An object is not a stand-alone program, but is used by programs that need its services.
Advanced Python
Classes
● In Python, a class is a blueprint for creating objects, which are instances of the class.
● A class defines the properties and behaviors of objects of a particular type.
● Class contain properties (variables) and methods (functions) of object.
Advanced Python
class ClassName:
Code….
my_object = ClassName()
my_object.member_function()
my_object.data_member
Advanced Python
Example 1
class Jafri:
my_data_member = “Hello!”
def my_member_function(self):
my_object = Jafri()
my_object.my_member_function()
print(my_object.my_data_member)
Advanced Python
Example 2
return self.sideup
Advanced Python
Example 2(Cont’)
my_coin = Coin() # Display the side of the coin that is facing up.
# Display the side of the coin that is facing up. print('This side is up:', my_coin.get_sideup())
print('This side is up:', my_coin.get_sideup()) # Call the main function.
main()
Advanced Python
Object:
Syntax:
object_name1 = ClassName()
Example:
class MyClass:
my_data_member = None
def my_member_function(self):
my_object = MyClass()
# Access the data member and call the member function of my_object
my_object.my_member_function()
Advanced Python
Data Member
Example:
class Student:
# Data members
student_id = 0
student_name = "Jafri"
# Creating Object
student = Student()
print(student.student_id)
print(student.student_name)
Advanced Python
Member Function:
● A member function, also known as a method, is a function that is defined within a class and
operates on the data members and other members of that class.
Advanced Python
# Member Function
def display_student_info(self):
Example 2:
# The BankAccount class simulates a bank account. def withdraw(self, amount):
Example 2(Cont’):
import bankaccount # Display the balance.
print('Your account balance is $',
def main(): format(savings.get_balance(), ',.2f'), sep='')
# Get the starting balance.
start_bal = float(input('Enter your starting # Get the amount to withdraw.
balance: ')) cash = float(input('How much would you like to
savings = bankaccount.BankAccount(start_bal) withdraw? '))
print('I will withdraw that from your account.')
# Deposit the user's paycheck. savings.withdraw(cash)
pay = float(input('How much were you paid this
week? ')) # Display the balance.
print('I will deposit that into your account.') print('Your account balance is $',
savings.deposit(pay) format(savings.get_balance(), ',.2f'), sep='’)
Advanced Python
● As mentioned earlier, it is a common practice to make all of a class’s data attributes private,
and to provide public methods for accessing and changing those attributes. This ensures that
the object owning those attributes is in control of all the changes being made to them.
● A method that returns a value from a class’s attribute but does not change it is known as an
accessor method.
● Accessor methods provide a safe way for code outside the class to retrieve the values of
attributes, without exposing the attributes in a way that they could be changed by the code
outside the method.
Advanced Python
● A method that stores a value in a data attribute or changes the value of a data attribute in some
other way is known as a mutator method.
● Mutator methods can control the way that a class’s data attributes are modified. When code
outside the class needs to change the value of an object’s data attribute, it typically calls a
mutator and passes the new value as an argument.
● If necessary, the mutator can validate the value before it assigns it to the data attribute.
Advanced Python
Self Keyword:
● The "self" keyword typically refers to a reference to the current instance of a class or object.
● It is a convention used to refer to the instance of a class within its methods.
● When you define methods within a class, you include "self" as the first parameter in the method's definition
to represent the instance itself
Example:
class MyClass:
self.value = value
def print_value(self):
print(self.value)
Advanced Python
obj = MyClass()
obj.Test(34)
obj.print_value()
Advanced Python
self.age = age
.
Advanced Python
Types Constructor:
▪ Parametrized Constructor
Advanced Python
class MyClass:
def __init__(self):
self.my_data_member = None
def my_member_function(self):
# Accessing the data member and calling the member function of my_object
my_object.my_member_function()
Advanced Python
print("A new car has been created!") # Output: "2020 Audi A4"
Advanced Python
Destructor Example
class Car:
def __init__(self):
def __del__(self):
my_car = Car()
Advanced Python
Inheritance
● Inheritance is a key feature of object-oriented programming (OOP) that allows one class to inherit
attributes and methods from another class.
● Inheritance allows a new class to extend an existing class. The new class inherits the members of the class
it extends.
● In Python, inheritance is implemented using the class keyword, and the parent class is specified in
parentheses after the class name.
● When one object is a specialized version of another object, there is an “is a” relationship between them.
For example, a grasshopper is an insect.
Syntax:
class Subclass(Superclass):
Advanced Python
Inheritance
● Base Class (Parent Class): There is only one parent class from which the child class inherits. The
parent class defines a set of attributes and methods that can be reused by the child class.
● Child Class (Derived Class): The child class inherits all the attributes and methods from the parent
class. It can also add its own attributes and methods or override the inherited ones to customize the
behavior.
Advanced Python
class ParentClass:
class ChildClass(ParentClass):
Example 01:
class Vehicle: # Call methods on the child class object
def drive(self):
car = Car()
Advanced Python
Example 02:
def method_b(self):
Types of Inheritance:
▪ Single Inheritance
▪ Multiple Inheritance
▪ Multi-level Inheritance
▪ Hierarchical Inheritance
Advanced Python
Single Inheritance:
● It refers to a type of inheritance in which a class (the child or derived class) inherits
properties and behaviors (attributes and methods) from a single parent class (the base or
parent class).
Advanced Python
Single Inheritance:
def parent_method(self):
class
my_object = Child()
print("This is the parent
method.") # Calling methods from both the
Parent and Child classes
class Child(Parent):
my_object.parent_method()
def child_method(self):
my_object.child_method()
print("This is the child method.")
Advanced Python
Multiple Inheritance:
● A class inherits from more than one superclass. This is achieved by specifying multiple
superclass names in parentheses separated by commas when defining the subclass.
Advanced Python
Example:
def child_method(self):
def parent1_method(self):
print("This is the child method.")
print("This is the parent1 method.")
# Creating an object of the Child class
class Parent2:
my_object = Child()
def parent2_method(self):
# Calling methods from all three classes
print("This is the parent2 method.")
my_object.parent1_method()
my_object.parent2_method()
my_object.child_method()
Advanced Python
Multi-level Inheritance:
● A class inherits from a superclass, which in turn inherits from another superclass.
Advanced Python
Example:
my_object.parent_method()
my_object.child_method()
Advanced Python
● Hierarchical Inheritance: A class has more than one subclass. This is achieved by defining
a superclass, and then defining multiple subclasses that inherit from the same superclass
Advanced Python
Example:
Access specifiers:
● Access specifiers are a way of controlling the access to attributes and methods of a class in
object-oriented programming languages like C++ and Java.
● Access specifiers define the level of access that other classes or objects have to the attributes and
methods of a class.
Advanced Python
● Private: By convention, attributes and methods that are intended to be private are named with a double
leading underscore (__), It can be accessed within classonly. Private access modifier is the most secure
access modifier.
● Protected: Attributes and methods that are intended to be protected are named with a single leading
underscore (_).
It can be accessed within the class, outside the class and child class
● Public: Incase of public, no need to put underscore before data member or method name
It can be accessed within the class, outside the class and child class
Advanced Python
Public:
Example:
Protected:
class MyClass:
def __init__(self):
def _protected_method(self):
Private:
class MyClass:
def __init__(self):
def __private_method(self):
Example:
# private member function # creating object
class Geek: def __displayDetails(self): obj = Geek("R2J", 1706256, "Information
Technology")
__name = None # accessing private data members
Polymorphism
▪ Method overloading
▪ Method overriding
Advanced Python
Method Overloading:
● In Python, method overloading is not supported in the same way as in other languages like Java
and C++. However, we can achieve similar behavior using default argument values and variable
arguments.
● With method overloading, we can define multiple methods with the same name but with
different parameter lists. When we call a method, the appropriate version of the method is called
based on the number and types of arguments passed to it.
Advanced Python
Example:
class Math:
return x + y + z
m = Math()
print(m.add(1, 2)) # 3
print(m.add(1, 2, 3)) # 6
Advanced Python
Method Overriding:
● Method overriding is the process of defining a method in a subclass that has the same name
and parameters as a method in its superclass.
● When the method is called on an object of the subclass, the version of the method defined in
the subclass is executed, rather than the version in the superclass.
Advanced Python
Example:
class Animal:
def speak(self):
print("Animal speaks.")
class Dog(Animal):
def speak(self):
print("Dog barks.")
a = Animal()
d = Dog()
super Keyword
● It is typically used within the child class to invoke a method that is overridden in the child class
but originally defined in the parent class.
● Using super keyword, we can access parent methods that are same with name.
● Its primary purpose is to provide a way to work with parent classes and their methods and
attributes in a child class.
Advanced Python
class Parent:
def __init__(self):
class Child(Parent):
def __init__(self):
super().__init__()
obj = Child()
Advanced Python
class Parent:
self.name = name
class Child(Parent):
super().__init__(name)
self.age = age
Advanced Python
class Parent:
def greet(self):
class Child(Parent):
def greet(self):
obj = Child()
obj.greet()