0% found this document useful (0 votes)
11 views7 pages

Oop Main Note Part 1

The document provides an overview of object-oriented programming (OOP) concepts, focusing on classes and objects, their creation, and methods. It explains the significance of encapsulation, inheritance, polymorphism, and abstraction as the core principles of OOP, along with practical examples in Python. Additionally, it discusses the use of the __init__ method and the self keyword in class definitions, and how encapsulation can restrict access to class attributes and methods.

Uploaded by

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

Oop Main Note Part 1

The document provides an overview of object-oriented programming (OOP) concepts, focusing on classes and objects, their creation, and methods. It explains the significance of encapsulation, inheritance, polymorphism, and abstraction as the core principles of OOP, along with practical examples in Python. Additionally, it discusses the use of the __init__ method and the self keyword in class definitions, and how encapsulation can restrict access to class attributes and methods.

Uploaded by

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

oop file:///home/mebinwobi/Documents/autograder/get211_cla...

In [ ]:

Classes
In object-oriented programming (OOP), a class is a fundamental concept that serves as a
template or blueprint for creating objects. A class de�nes the properties (attributes)
and behaviors (methods) that the objects created from it will have. It encapsulates data
for the object it represents, specifying the characteristics and actions that entities of
the class can perform. By using classes, programmers can create complex data
structures that model real-world entities or abstract concepts in a manageable,
modular, and organized manner. A class acts as a user-de�ned data type, with the
unique characteristic that it not only de�nes the data (as in, the structure of the data)
but also the operations (methods) that can be performed on that data. This
encapsulation of data and functions into one single entity (the class) is a core principle
of OOP, aiming to increase the modularity and reusability of code.

Objects
In the realm of object-oriented programming (OOP), an object is a fundamental concept
that serves as the cornerstone of its design and implementation strategies. An object
can be understood as an encapsulation of data, along with the methods that operate on
that data, packaged together as a single entity. This concept allows programmers to
model and organize complex systems by mimicking real-world entities and their
interactions. At its core, an object represents an instance of a class. A class, in turn, acts
as a blueprint or template from which objects are created. It de�nes the attributes (also
known as properties) and behaviors (known as methods) that its objects will have.
Attributes represent the state of an object, while methods de�ne its actions or
functionalities.

For example, in a school management system, there could be a Student class with
attributes such as �rst name, last name, registration number, sex, phone number, level
of study, and methods like promote(), pay_fees(), and register_course().

Creating Objects
Creating objects in object-oriented programming (OOP) is the process of instantiating
classes, which means bringing class blueprints to life by allocating memory for the
objects and setting up their initial state. (i.e. providing values for attributes). In Python,
objects are created from classes through a straightforward and intuitive syntax. This
process not only marks the creation of an instance of a class but also serves as a pivotal
point where the abstract de�nitions within a class become concrete entities that can
interact within your program. We'll demonstrate with the creation of a Person class.

In [17]: class Person:

def __init__(self, name, age):


self.name = name

1 of 7 3/26/25, 21:38
oop file:///home/mebinwobi/Documents/autograder/get211_cla...

self.age = age

def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."

Instantiating an Object

To create an object (also known as an instance) of the Person class, you simply call the
class using its name followed by the parentheses, passing any required arguments that
the class constructor (the __init__ method) de�nes.

In [18]: person1 = Person("Alice", 30)

At this point, person1 is an object of the Person class, with its name set to "Alice" and
age set to 30. The __init__ method is automatically called during object creation,
initializing the object's attributes.

Once an object has been created, you can acces its attributes and methods using the dot
notation. This allows you to perform operations that are de�ned withing the class.

In [19]: print(person1.greet())

Hello, my name is Alice and I am 30 years old.

You can now create as many person objects as you need with the guarantee that you can
interact with them in a consistent manner.

In [20]: person2 = Person("Bob", 25)


print(person2.greet())

Hello, my name is Bob and I am 25 years old.

Although person1 and person2 are objects of the Person class, the values of the
attributes in each instance is separate.

Methods
Methods in object-oriented programming (OOP) are functions that are de�ned inside a
class and are intended to be called on objects that are instances of that class. Methods
allow objects to perform operations on their data attributes or to execute any actions
that are relevant to the object. Understanding how methods work is crucial for
leveraging the full potential of OOP, as they encapsulate the behavior of the objects.

De�ning and calling methods

Methods are de�ned withing a class using the def keyword, similar to any other function
in Python. However, the key di�erence is their �rst parameter, which is always self by
convention. The self parameter is a reference to the instance of the class on which
the method is being called. This allows the method to access the attributes and other
methods of the object, enabling interaction and manipulation of the object's internal
state (values of the attributes.) We have seen this in the Person class where we
de�ned the greet method.

2 of 7 3/26/25, 21:38
oop file:///home/mebinwobi/Documents/autograder/get211_cla...

Types of Methods

In Python, there are three types of methods that you can de�ne within a class: instance
methods, class methods, and static methods.

Instance methods: Theses are the most common type of methods, which operate on an
instance of the class and have access to the self parameter, allowing them to modify
the object's state or return information about the object's state. The greet method in
the Person class is an instance method.

Class Methods: Class methods operate on the class itself rather than instances of the
class. They are marked with a @classmethod decorator, and instead of self ., the
take cls as their �rst parameter, which represents the class. Class methods can
modify class state that applies accross all instances of the class.

Static Methods: Static methods are marked with a @staticmethod decorator and do
not take a self or cls parameter. Consequently, they cannot modify object or class
state. These methods are restricted in what data they can access and are used when
some functionality is logically tied to a class but does not access any class or instance-
speci�c data.

We can demonstrate class methods and static methods with a class that computes the
distance from a point to the equator and the distance between a point ϕ and the center
of the earth.

The formula for calculating the distance from the equator (in kilometers):

Distance = Lattitude ∗ 111


The formula for calculating the distance from lattitude ϕ to the center of the earth:

 2 2
 (Re cos ϕ + Rp sin2 ϕ)
R=
2



2
(cos 2 ϕ + Rp sin2 ϕ)
2
Re

Where:

• R = Distance from Earth's center to a point at latitude ϕ.


• Re = Equatorial radius (approx. 6,378.137km)
• Rp = Polar radius (approx. 6,356.752 km).
• ϕ = Latitude in degrees

In [21]: from math import sqrt, sin, cos, radians

class EarthDistanceEstimator:
# We define R_e and R_p as class attributes
# because they do not change from instance to
# instance

# You can use underscores in place of commas


# to make large numbers readable

3 of 7 3/26/25, 21:38
oop file:///home/mebinwobi/Documents/autograder/get211_cla...

R_e = 6_378.137
R_p = 6_356.752

@classmethod
def distance_from_center(cls, lattitude):
# convert lattitude from degree to radians
# because `sin` and `cos` in the math library
# takes angles in radians
lat_rads = radians(lattitude)
numerator = (cls.R_e*cos(lat_rads))**2 + (cls.R_p*sin(lat_rads))**
denominator = cos(lat_rads)**2 + (cls.R_p * sin(lat_rads) / cls.R_e
distance = sqrt(numerator / denominator)
return distance

@staticmethod
def distance_from_equator(lattitude):
# We define a method for calculating the
# distance from the equator as a static
# method because it does not need any
# instance or class attributes
return lattitude * 111

# We do not need to create an instance of the class to


# use the `distance_from_center` class method
d1 = EarthDistanceEstimator.distance_from_center(50)
print(
f"The distance between a point on latitude 50"
f" degrees and the center of the earth is {d1} KM"
)
# Just like for class methods, we also do not need to
# create an instance of the class to use the
# `distance_from_equator` static method
dist_from_equator = EarthDistanceEstimator.distance_from_equator(50)
print(
f"The distance between a point on lattitude 50"
f" degrees and the center of the earth is "
f"{dist_from_equator} KM"
)

The distance between a point on latitude 50 degrees and the center of the
earth is 6378.137 KM
The distance between a point on lattitude 50 degrees and the center of the
earth is 5550 KM

The init method and self

The __init__ method and the self keyword are two fundamental aspects of class
de�nitions in Python, playing a crucial role in object-oriented programming.
Understanding these concepts is essential for creating classes that initialize their
objects correctly and for writing code that is clear, maintainable, and e�ectively utilizes
the OOP paradigm.

*The __init__ method: The_ init_ method in Python is a special method, also
referred to as a constructor. It is automatically invoked when a new object of a class is
created. The primary purpose of the_ init_ method is to initialize the newly created
objects attributes with speci�c values. Essentially, it sets the initial state of the object.

4 of 7 3/26/25, 21:38
oop file:///home/mebinwobi/Documents/autograder/get211_cla...

The name_ init_ is preceded and followed by double underscores (also called "dunder"
for double underscore), indicating that it is a special method in Python. It's important to
note that_ init_ doesn't explicitly return a value; its return value is always None. Instead,
it modi�es the state of the object.

The self keyword: The self keyword in Python is a reference to the current instance of
the class. It is used to access variables and methods associated with the current object.
In the de�nition of a method within a class, self is always the �rst parameter, although it
is not a keyword in the Python language itself but a convention that is strongly
followed. When a method is called for an object, Python implicitly passes the object to
the method as the �rst parameter.

Pillars of Object-oriented Programming


There are four core principles of OOP:

1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

Encapsulation: This refers to the bundling of the data (attributes) and the methods that
operate on the data into a single unit, the object. More importantly, encapsulation is
about restricting access to the inner workings of that class from the outside world,
thereby creating a "black box" e�ect. This is achieved through the use of access
modi�ers, which can restrict access to the class components from code outside the
class. In Python, encapsulation is implemented through the use of public, protected, and
private access modi�ers, though it's important to note that these are enforced only by
convention.

The primary purpose of encapsulation is to protect the object's integrity by preventing


outsiders from setting its internal state into an inconsistent or invalid state. This is
achieved by controlling how its data can be accessed or modi�ed. Encapsulation allows
the internal representation of an object to be changed without a�ecting the external
way in which the object is accessed.

One of the main mechanisms encapsulation employs to achieve this protection is


through the use of access modi�ers, such as private, protected, and public. By marking
the attributes of a class as private, a programmer can restrict access to the class's
internal state, making it accessible only through methods of the class. These methods —
often referred to as getters and setters — provide a controlled way to retrieve or
update the values of private attributes. This control mechanism ensures that any
updates to the object's state can be validated, keeping the object in a consistent and
valid state.

Furthermore, encapsulation allows the internal workings of an object to be hidden from


the outside world. This means that the implementation details of how an object
performs its tasks are kept separate from the interface the object presents to the

5 of 7 3/26/25, 21:38
oop file:///home/mebinwobi/Documents/autograder/get211_cla...

outside world. As a result, changes to the internal implementation of a class, such as


optimizing the code or �xing bugs, can be made without a�ecting the parts of the
program that use the object. This property of encapsulation facilitates a modular design
approach, where individual parts of a program can be developed, tested, and modi�ed
independently.

Restricting access to attributes and methods in Python

In python, all object attributes and methods are public by default. Python adopts a
convention to de�n private members, which is by pre�xing the name of the member
with a single underscore __ .

In [22]: class BankAccount:


def __init__(self, acct_number, initial_deposit=0):
self.account_number = acct_number
self.__balance = initial_deposit

def deposit(self, amount):


self.__balance += amount
print(
f"Credit Alert of {amount}NGN. "
f"New balance: {self.__balance}NGN"
)

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
print(
f"Debit Alert of {amount}NGN. "
f"New balance: {self.__balance}NGN"
)
else:
print(
f"Transaction failed. Insufficient funds."
)

def transfer(self, amount, other_account):


if amount <= self.__balance:
self.withdraw(amount)
other_account.deposit(amount)
print(
f"Transfer to "
f"{other_account.account_number}"
f"successful. Amount: {amount}NGN."
)

In [ ]:

Inheritance: Inheritance allows one class (the child class) to inherit the attributes and
methods of another class (the parent class or base class), facilitating code reuse and the
creation of hierarchical organization of classes.

Inheritance allows a subclass to inherit attributes and methods from a superclass,


enabling the subclass to reuse code without having to rewrite existing functionality. The
subclass can also modify (override) inherited methods, extend the superclass by adding

6 of 7 3/26/25, 21:38
oop file:///home/mebinwobi/Documents/autograder/get211_cla...

new methods and attributes, and provide new implementations for existing methods.
This capability to extend and customize the behavior of a superclass makes inheritance a
powerful tool for code organization and reuse.

to be continued...

7 of 7 3/26/25, 21:38

You might also like