OOP Part 1
OOP Part 1
Object-Oriented Programming
● Object-oriented technology models real-world objects.
● Real-world objects are things around you, such as:
table, television, chair, etc.
Class Object
Inheritance Polymorphism
OOP
Data
Encapsulation Abstraction
Advantages of OOP
What is an Object
An object (instance) is an instantiation of
a class.
Defining a Class in Python class Person:
name = str()
age = int()
class classname:
statements..... def set_details(self, n, a):
self.name = n
self.age = a
def display(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
print(f"Is {self.name} an adult?:
",end="")
The __init__ function
The __init__() function/method is called automatically every time
the class is being used to create a new object.
class Person:
def __init__(self, name,
age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
def __init__(self,
name,age,address):
self.pangalan = name
self.edad = age
self.lugar = address
student = Person("John","30","Iloilo
City")
print(f"My name is
{student.pangalan} ")
print(f"Im {student.edad} years
old")
print(f"I live in {student.lugar} ")
Object Methods
def myfunc(self):
print("Hello my name is " +
self.pangalan)
p1 = Person("John", 36)
p1.myfunc()
Access Modifiers
Python uses ‘_’ symbol to determine the access control for a specific
data member or a member function of a class. Access specifiers in
Python have an important role to play in securing data from
unauthorized access and in preventing it from being exploited.
The members of a class that are declared private are accessible within
the class only, private access modifier is the most secure access
modifier. Data members of a class are declared private by adding a
double underscore ‘__’ symbol before the data member of that class.
def __greet():
print(“hello”)
Protected Access Modifiers
The members of a class that are declared protected are only accessible
to a class derived from it. Data members of a class are declared
protected by adding a single underscore ‘_’ symbol before the data
member of that class.
def _greet():
print(“hello”)
Public access modifiers
All the class members can be accessed anywhere inside or
outside the class,
All data members and member functions of a class are public
by default.
class Computer:
def __init__(self):
self.__maxprice = 900
Encapsulatio
def sell(self):
print(f"Selling Price: {self.__maxprice}")
n
def setMaxPrice(self, price): - can restrict access
self.__maxprice = price
to
comp = Computer() methods and
comp.sell() variables.
print("==================")
- it prevents data
# change the price directly
comp.__maxprice = 1000 stored
comp.sell() inside the
# using setter function attributes
print("==================")
comp.setMaxPrice(1000) from direct
comp.sell() modification
Data Encapsulation
Create a class BankAccount that encapsulates the
details of a bank account. The class should have the
following features: