University of Antique Tario-Lim Memorial Campus
College of Computer Studies
CPROG 3
Object Oriented
Programming Revised by REX P. BERNESTO
Subject Instructor
INSYSE 1 BAN – Enterprise Systems
Copyright from JUDITH U. LAGOS
Prepared by:
Juvelyn Samillano
Robilyn Banlig
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Chapter 2 Classes and Objects
Object Oriented means directed towards objects. In other words, it means functionally
directed towards modelling objects. This is one of the many techniques used for modelling
complex systems by describing a collection of interacting objects via their data and behavior.
Python, an Object Oriented programming (OOP), is a way of programming that focuses on
using objects and classes to design and build applications. Major pillars of Object Oriented
Programming (OOP) are Inheritance, Polymorphism, Abstraction, ad Encapsulation.
Object Oriented Analysis(OOA) is the process of examining a problem, system or task and
identifying the objects and interactions between them.
Modules
A file containing a set of functions you want to include in your application. Module is a
specialized dictionary that can store Python code so you can get to it with the ‘.’ Operator.
Modules are like “Dictionaries”
When working on Modules, note the following points:
A Python module is a package to encapsulate reusable code.
Modules reside in a folder with a __init__.py file on it.
Modules contain functions and classes.
Modules are imported using the import keyword.
To create a module just save the code you want in a file with the file extension .py:
Example:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
import mymodule
mymodule.greeting("Jonathan")
Class - is like an object constructor, or a "blueprint" for creating objects
How to Create a Class
To create a class, use the keyword class:
Example:
class MyClass:
x = 5
class Animal:
print(“A Dog”)
Object - An Object is an instance of a Class.
o How to Create an Object
Create an object named p1, and print the value of x:
Example:
p1 = MyClass()
print(p1.x)
• The __init__() Function
All classes have a function called __init__(), which is always executed
when the class is being initiated.
Use the __init__() function to assign values to object properties, or other
operations that are necessary to do when the object is being created:
Example:
class Person:
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
▪ Attributes – are properties associated with objects. They can be variables or
methods that are defined within a class or an instance of a class.
Class Attributes - variables that are associated with a class rather than with instances
(objects) of that class.
Example:
class MyClass:
class_attribute = "I am a class attribute"
# Accessing class attribute
print(MyClass.class_attribute)
# Modifying class attribute
MyClass.class_attribute = "New value for class attribute"
print(MyClass.class_attribute)
Instance Attributes - variables that belong to an instance of a class. Unlike class
attributes, which are shared among all instances of a class, each instance attribute is specific
to a particular object created from that class.
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
▪ Methods - Objects can also contain methods. Methods in objects are functions that
belong to the object.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self Parameter- The self parameter is a reference to the current instance of the class, and
is used to access variables that belong to the class.
Example:
class Person:
#Use the words mysillyobject instead of self:
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
▪ Modify Object Properties
- You can modify properties on objects like this:
- Set the age of p1 to 40:
Example : p1.age = 40
▪ Delete Object Properties
- You can delete properties on objects by using the del keyword:
- Delete the age property from the p1 object:
Example : del p1.age
▪ Delete Objects
- You can delete objects by using the del keyword:
Example : del p1
▪ The pass Statement
class definitions cannot be empty, but if you for some reason have a class
definition with no content, put in the pass statement to avoid getting an error.
Example : class Person:
pass
Section 3: Constructors and Destructors
A constructor is a special method (`__init__`) that initializes an object’s attributes when the object is
created.
A destructor is a special method (`__del__`) that is called when an object is about to be destroyed.
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
print(f"Book '{self.title}' by {self.author} created.")
def __del__(self):
print(f"Book '{self.title}' is deleted.")
book1 = Book("Python Programming", "John Doe")
del book1
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Inheritance
INHERITANCE
Inheritance - allows us to define a class that inherits all the methods and properties of
another class.
Parent Class - is the class being inherited from, also called base class.
▪ How to create a Parent Class
- Any class can be a parent class, so the syntax is the same as creating any other
class:
Example :
Create a class named Person, with firstname and lastname properties, and
a printname method:class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname method:
x = Person("John", "Doe")
x.printname()
Child Class – is the class that inherits from another class, also called derived class.
▪ How to create a Parent Class
To create a class that inherits the functionality from another class, send the parent class as
a parameter when creating the child class:
Example:
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Create a class named Student, which will inherit the properties and methods from the
Person class:
class Student(Person):
pass
#Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
▪ Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note:The __init__() function is called automatically every time the class is being used to
create a new object.
Example:
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.
Note: The child's __init__() function overrides the inheritance of the parent's __init__()
function.
To keep the inheritance of the parent's __init__() function, add a call to the parent's
__init__() function:
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Example:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.
▪ Use the super() function
Python also has a super() function that will make the child class inherit all the methods and
properties from its parent:
Example:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, you do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
▪ Add Properties
Add a property called graduationyear to the Student class
Example:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into the Student class
when creating student objects. To do so, add another parameter in the __init__() function:
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Example:
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
▪ Add Methods
Example:
Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
If you add a method in the child class with the same name as a function in the parent class, the
inheritance of the parent method will be overridden.
Encapsulation - encapsulation refers to the bundling of data (attributes) and methods
(functions) that operate on the data into a single unit, typically a class. Encapsulation is the
process of hiding the internal state of an object and requiring all interactions to be performed
through an object’s method.
It also restricts direct access to some components, which helps protect the integrity of the
data and ensures proper usage.
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
ENCAPSULATION Python achieves
encapsulation through public,
protected and private attributes.
How Encapsulation Works :
Data Hiding: The variables (attributes) are kept private or protected, meaning they are not
accessible directly from outside the class.
Access through Methods: Methods act as the interface through which external code interacts
with the data stored in the variables.
Control and Security: By encapsulating the variables and only allowing their manipulation via
methods, the class can enforce rules on how the variables are accessed or modified, thus
maintaining control and security over the data.
• Public Members
are accessible from anywhere, both inside and outside the class. These are the default
members in Python.
Example:
class Public:
def __init__(self):
self.name = "John" # Public attribute
def display_name(self):
print(self.name) # Public method
obj = Public()
obj.display_name() # Accessible
print(obj.name) # Accessible
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Public Attribute (name): This attribute is declared without any underscore prefixes. It is
accessible from anywhere, both inside and outside of the class.
Public Method (display_name): This method is also accessible from any part of the code. It
directly accesses the public attribute and prints its value.
Object (obj): An instance of Public is created, and the display_name method is called,
demonstrating how public attributes and methods can be accessed directly.
• Protected Members
are identified with a single underscore (_). They are meant to be accessed only within
the class or its subclasses.
Example:
class Protected:
def __init__(self):
self._age = 30 # Protected attribute
class Subclass(Protected):
def display_age(self):
print(self._age) # Accessible in subclass
obj = Subclass()
obj.display_age()
Protected Attribute (_age): This attribute is prefixed with a single underscore, which by
convention, suggests that it should be treated as a protected member. It’s not enforced by
Python but indicates that it should not be accessed outside of this class and its subclasses.
Subclass: Here, a subclass inherits from Protected. Within this subclass, we can still access
the protected attribute _age.
CPROG 3 – Object Oriented Programming
University of Antique Tario-Lim Memorial Campus
College of Computer Studies
Method (display_age): This method within the subclass accesses the protected attribute and
prints its value. This shows that protected members can be accessed within the class and its
subclasses.
• Private members
are identified with a double underscore (__) and cannot be accessed directly from
outside the class. Python uses name mangling to make private members inaccessible by
renaming them internally.
Note: Python’s private and protected members can be accessed outside the class through
python name mangling.
Example:
class Private:
def __init__(self):
self.__salary = 50000 # Private attribute
def salary(self):
return self.__salary # Access through public method
obj = PrivateExample()
print(obj.salary()) # Works
#print(obj.__salary) # Raises AttributeError
Private Attribute (__salary): This attribute is prefixed with two underscores, which makes it a
private member. Python enforces privacy by name mangling, which means it renames the
attribute in a way that makes it hard to access from outside the class.
Method (salary): This public method provides the only way to access the private attribute from
outside the class. It safely returns the value of __salary.
Direct Access Attempt: Trying to access the private attribute directly (obj.__salary) will result
in an AttributeError, showing that direct access is blocked. This is Python’s way of enforcing
encapsulation at a language level.
CPROG 3 – Object Oriented Programming