0% found this document useful (0 votes)
6 views18 pages

Object-Oriented Programming in Python

Uploaded by

Anjum Verma
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)
6 views18 pages

Object-Oriented Programming in Python

Uploaded by

Anjum Verma
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

Module – 14

Object-Oriented
Programming
Object- Oriented Programming

Table of Contents

1. The Concept of Class and an Object ............................................................................................... 4

2. Python Class, Methods, Members, Objects .................................................................................... 6

2.1 Analogy – Bank Based Class ....................................................................................................... 7


3. Concept of __init__ .......................................................................................................................... 10

4. Updating Values using Methods ................................................................................................... 14

5. Inheritance ...................................................................................................................................... 17
Module Description

Object-Oriented programming (OOP) is structuring a program by bundling related properties


and behaviors into individual objects.

This module includes the following topics:

• The Concept of Class and an Object


• Python Class, Methods, Members, Objects
• Concept of __init__
• Updating Values using Methods
• Inheritance

Learning Objectives

By the end of this module, you will be able to:

• Classify the core concepts of object-oriented programming


• Design classes and objects
• Describe member attributes and methods
• Describe the concept of Self
• Explore __init__method
• Explain updating the values of data members using methods
• Explain inheritance in object-oriented programming in Python
1. The Concept of Class and an Object

This topic will cover core concepts of object-oriented programming in general.


Till now, you have probably been coding in your so-called procedural style. Your code was a
sequence of steps to be carried out. Like you might have created a list and worked with it. We
do a lot of data analysis this way, like we download the data, process it, visualize it, etc. So
procedural thinking is very natural.

You pick an egg, boil it, and eat it. This sequential viewpoint works great if you're trying to have
breakfast or trying to plan your day, etc.
But let's say you're a car manufacturer, you must think about 1000s of parts in a car, and a
similar car being used by 1000s of people. Trying to map out a sequence of actions for each
one of those car parts could be difficult for mass production.
Instead, you create a plan and blueprint for creating multiple cars. When you decide upon the
set of parts required for a single car, you jot them down, then procure them in great numbers,
and later, an assembly line in a factory puts them together to create multiple cars. That
assembly unit is like a class consist of Blueprint of a single car as a single object.

Now this car is an object that can be used to transport people and goods. A car has engines,
four wheels, several doors, and a lot of other mechanical and electrical parts. These parts are
hidden under the hood. A driver controls the car using a steering wheel, the accelerator, or the
gas, brake pedals, many buttons, and switches on the dashboard, probably. If you're driving a
car and want to make it go faster, you press its gas pedal which will consume the fuel of your
car. The specific car you drive is one of the many cars of a particular model, that was made by a
car factory, according to a specific designer blueprint. The blueprint of the car may contain a
set of engineering drawings, documents, and a list of parts that specify the details of building
the car.

Specifically, the blueprint will include the steering wheel gas, brake pedals, etc. The gas pedal
hides the mechanism from the driver/the user of the car, which makes the car go faster. The
brake pedal hides the mechanism that slows the car, and the steering wheel hides the
mechanism that turns the car. This enables people with little or no knowledge of how engines,
braking, and steering mechanisms work to drive a car easily and safely. To be able to use a car
or to travel, the car must be made by a factory.

There are two perspectives here, the user who drives a car who has little or no knowledge
about mechanisms here, and the car manufacturer who created the car and knows all
mechanisms working. In computer software, an object is used to keep and modify information,
so each car becomes an object here. This object is also made according to a blueprint and used
by a user like a programmer.
2. Python Class, Methods, Members, Objects

In Python, every data that you create is an object, even functions are treated as objects. When
you create a list and print the type of this list, it belongs to a class called a list.

Figure 14.2.1 lista

There is an internal class called a list, and lista is an object of that class.

Figure 14.2.2 Available methods

When you write lista and press tab, you get a set of all the methods that you have for this
object. All these methods are part of the internal class list, it is extended to any kind of list-
based objects that you create. If you write [Link], it is already a function or appropriately
called a method and it belongs to the internal class list. It is accessible to any list-based objects
like lista. If lista is a user's count, so to count the number of times ‘aa’ occurs, it will show like 3
times as shown in figure 14.2.3. So lista is an object of the type of class list.

Figure 14.2.3 lista count for ‚aa’


If you create an integer variable, say equals to 400. Now even this is an object of the type
integer.

Figure 14.2.4 Integer variable

So, before you could go ahead and understand the way to create Python class methods,
members, and objects, you should know that each data in Python is an object, even functions
are treated as objects.

2.1 Analogy – Bank-based Class

Now, let’s create another analogy to understand class. Here class is the keyword for creating a
class, followed by the name of the class, which you will give as a bank.

Now, what attributes can a bank have?


Let's say, for every customer, you have an account number, and after he/she opens the bank
account, they may have an initial deposit amount. Eventually, there will be an account balance,
name, etc. There is a lot of data that we can store in a bank-based object, but for now, let’s go
with this four for now.

What kind of methods or what kind of actions may be taken for a bank-based object?
The simplest may be to withdraw some money or to deposit some amount and check out the
balance. This here is a dummy code, so not executing it.

Alright, so this is a typical class. Now, if you create bank objects, each bank object will have
access to its own account number, initial deposit amount, own account balance, name, etc. This
combination of data and methods or data and functions make it a comprehensive class.

Figure 14.2.5 Bank based class


Well, C or C++ kind of programmers generally tends to use the term function. Java
programmers tend to use the term methods. In Python, you don't have a rule as such.

A class is like a blueprint, which can be used to create objects.

Moving ahead, keep this code as a dummy for now and create a simpler class, calling it a
sample with two data members, data_a and data_b. Add a method to display the values of
these data.

Figure 14.2.6 Sample class

Now, how do you create an object for this class?


The creation of an object is done by equating it to the class name followed by brackets. So
there, object x equals sample, and object y equals sample. With the syntax, you have created
two objects, and these objects are of the type class sample.

Figure 14.2.7 Object x and y

Now, if you need to use the method display, there is an additional step. In Python, you need to
add this object called self. Two things to keep in mind here, first, self is not a keyword, and
second, you could have written anything apart from self. But the self is the convention that
Python programmers use globally.

This self is like a placeholder. It represents the instance of the class. By using the self, you can
access the attributes and methods of the class in Python, meaning, it represents the object.
Object x can call its own display method and it can access its own values of data_a and data_b.

[Link]() [Link]()

Self will represent objx and take you Self will represent objy and take you
to data_a and data_b of object x to data_a and data_b of object y
So, when you call object x display, then self will represent object x and take you to data_a and
data_b of object x. When you call object y display, then self will represent object y and take you
to data in the database of object y. And that is the reason you must use self for each of the
methods in the Python class.

Figure 14.2.8 Object value for x

Printing object x for data_a is 20, and if you print the same thing using the display method, you
get it as 20, and the other data member is 30. These were the initialized values. The value will
remain the same for both objects unless, of course, changed explicitly.

Now, let’s change the value of data_a of object x to 100, it becomes 100. Let us display this
using the display method. However, data values for the object y are still 20 and 30.

Figure 14.2.9 Object value for y

In this topic, you understood the concept of class, data, members, and methods inside a class.
You created a sample class and its objects. The important takeaway here is that the self
function is used when you create a method, and if you are accessing data within the method,
you need to write the self. (dot) and then the attribute name.
3. Concept of __init__

In this topic, you will understand the concept of a special method call as init.
Create a new notebook, name it as two and copy the dummy code of the bank-based class in
this notebook. In this class, you had some member attributes like account number, initial
deposit, etc., and some functions or methods such as withdrawal, deposit, check balance, etc.

Figure 14.3.1 Bank based class

You can give default initial values to the data members, like you have done in the last topic to
sample class, or you can efficiently give a fresh set of values to corresponding data members
every time you create a new object.

You can initialize each object with a different set of values, which are as per the object
requirements.

How would that be possible?


It is possible by using a built-in method called as __init__.
It is a special method and needs to maintain the same spelling and format (two underscores
init two underscores).
Programmers with basic OOP knowledge in other languages may recall the concept of a
constructor to understand this.
The __init__ method is not exactly a constructor but quite similar.

Features of __init__ Method:

• The __init__ method gets called automatically, which means it is not required to be called
explicitly.
• It gets called by default whenever an object is created.
• It gets called for each object that you create.
Advantages of __init__ Method:
• While creating an object, you can put certain values which will be received by the __init__
method.
• It helps you to create an object and initialize all the data members of that object at the
beginning.
• It also enables you to give different values to different objects.

In simple words, create an object while creating pass certain values, those values will be passed
on to the data members automatically with the help of init.

In the code, add arguments in it. Now, this x, y, and z will receive values when an object is
created. But for now, without completing the code, go to the next cell. Create two objects like
object J and object p using the class blank.

Now, what if you wanted to give values to these objects during the creation of the object itself?
Like account number, initial deposit, and name, now the name John Lennon automatically gets
stored in z, initial amount 500 gets stored in y account number, 245026 automatically gets
stored in x as shown in figure 14.3.2.

Figure 14.3.2 Self x,y, and z

For now, assume that these values have reached XYZ, how are you going to pass this exactly to
the data members of that object?
You know that self represents the object, and it already has a self. If you prefix self to the
account number, initial deposit, etc., all those data members will become exclusive to their
objects.

First, add self. to the account number, initial deposit, account balance, and name, as shown in
figure 14.3.3. When you do this, [Link] is equated to x means, 24502 is now
stored in object x account number, [Link] equals y, which would be 500.
When you open an account, [Link] is going to be the same as the initial deposit
and equate it to y. [Link] equals z, which stands for John Lennon in the first case.

Figure 14.3.3 Add self. commad

Explaining this once again, you create object J as an object of class band. And while doing so,
you pass three values, these three values are automatically stored in x, y, and z, respectively.
You could have used any terms there; just use xyz for simplicity. Once these values have
reached it, pass them on to account number, initial deposit account balance, and name,
respectively.

While doing so, you are using self because self here is going to represent the object J, creating
another object p. Even for object p, the init method will be called automatically, and xyz will get
values of 245028, 1000, and Paul McCartney as the name, respectively; these will be passed and
stored to account number, initial deposit account balance, and the name.

Figure 14.3.4 Objj and objp

Okay, before you execute, add a print statement to it. When objects are created, it will be called
for each object, so you will get to see two prints here.

Figure 14.3.5 Adding print statement


You also need to have a proper definition for other methods like withdrawal, deposit, check
balance, etc. For now, use the keyword pass to syntactically complete the code. Execute the
statement. You can see the two print statements. Because the init was called for both the
objects separately, object J got the data for John Lennon and object p got the data for Paul
McCartney.

Figure 14.3.6 Output statement

This is your definition of the class within it. It's no longer a non-executable or a dummy code.
It's a blueprint for creating multiple objects. Try printing out one of the values, say
[Link], and it is giving you a value of 500. With this, you got a detailed look at
the init method.

Figure 14.3.7 Account balance


4. Updating Values using Methods

Here you will work on the same notebook file ([Link]) that you had created in the previous
topic.

Deposit Method

Ideally, the programmer would want to run the deposit method with the object J, maybe
depositing $700.

Figure 14.4.1 [Link]

Your deposit method should be able to take the $700, that is why you will create new data as
amt. You should know if you're going to deposit some money in the account, your account
balance would increase. So that is why [Link] equals [Link] plus
amt. Now, inform the customer that his or her account has been credited with so many dollars
and tell him or her that your updated balance or new account balance is so much.

Figure 14.4.2 Print statement for deposit

What happens here is, if somebody calls for objectj or deposit and passes 700, that goes to
amt, and since cell 3 presents the object, so objectj account balance gets incremented by 700.

Withdraw Method

Now the same logic would apply to withdrawal as well. However, withdrawal would have one
more extra catch; you will have to check if the money that is being requested for withdrawal is
less than the account balance.

The code will be [Link], let's say is asking to withdraw 700. So that will go and get
stored in amt.
Here first, you need to check if [Link] is greater than or equal to amt. The
account balance currently should be more or equal to $700. And if it's so, then the account
balance gets deducted by amt by 700. And again, same or similar print statements to inform
the client and customer that your account has been debited.
Figure 14.4.3 Print statement for successful withdrawal

Now this condition of [Link] greater than equal to the amount is satisfied. Now,
add the code that follows what if this condition is not satisfied, let's just print and display to the
client that you do not have enough balance.

Figure 14.4.4 Print statement for error in withdrawal

Check Balance

If the user wants to check their balance, you can write welcome and put their name in there.
It will be as welcome, John Lennon or welcome, Paul McCartney, and display the account
balance.

Figure 14.4.5 Print statement for check balance

This init, deposit, withdraw, and check balance are the four methods which are there in this
class called as a bank init which gets called automatically for the rest of the methods. You will
have to explicitly call them in the code.

Run the codes again because the bank class has changed. The code for the class has changed
the objects that were created were from the earlier class. You need to run this again. You have
fresh objects now.

When you try to withdraw 700, it says you do not have enough balance. Obviously, because
object j, that is, John, had only 500 as an opening balance that continued as the account
balance.

Figure 14.4.6 Withdrawal 700


Now, deposit a certain amount. Deposit 400, the new account balance would become 900.

Figure 14.4.7 Deposit of 400

Now, check the balance as well. And it does say that my balance is $900.

Figure 14.4.8 Check balance

Now, try and withdraw 700. Again, this time you shouldn't get an error. The account has been
debited, and the new balance of 900 minus 700 is 200.

Figure 14.4.9 Withdrawal of 700

This is a sample bank class in an actual bank class used in a bank; you will have a lot of data
and a lot of methods. This class Bank is a blueprint that can be used to create multiple objects.
5. Inheritance

What is Inheritance?

• It is a simple English term.


• You inherit a lot of properties and features from your parents.
• In coding, you can extend the functionality of an existing class.
• You can modify that class, but there is a good chance you will make it complicated or
break something that was already working.
• You can write a new class, but it is again adding more codes.

Let's say you have a class called the vehicle. Now think about vehicles, bikes, cars, buses, and
trucks. All share the characteristics of vehicles, but each one of them has additional features.
Keeping that in mind, what you can do is you can implement a vehicle as a base class in Python,
whereas cars, buses, and trucks can be implemented as subclasses, which will inherit from the
vehicle.

Taking back your banking example, you created a class for the bank. Now there can be
different kinds of banks like credit unions, commercial banks, etc. Your base class is a bank, or
you can also call it as a parent class, from there, you can derive out a child, which can be a
credit union; it will have all the features that the parent bank class has. Plus, it can have some
more extra features for itself.

Inheritance really enables you to define a class and take all the functionality from a parent class
and probably allow you to add more. It is really a powerful feature in object-oriented
programming.

Now let's see how you can create this in the Python syntax.

Let’s say you have a class called Unix, this is just an analogy, and it is not really a code that will
create a Unix OS, just for explanation purposes.
Unix is one of the older operating systems, and it has a great command line. It is quite secure
as well because of the concept of RWX.
Now, create a function or a method called a cmd. Unix is a class that has two methods cmd and
secure.

Figure 14.5.1 Class Unix


Now, create a class called Linux, which is free and open source, to define this method. Now
Linux is a derivative of Unix. So instead of copying these functions or rewriting this method,
what you can do is make Linux get the features of Unix plus add its own features. To do this,
add Unix in the brackets after the class Linux.

Figure 14.5.2 Class Linux

Now, what happens is the Linux class gets all the features of Unix plus the extra feature it
created for itself that is free.

If I create an object of the type of Unix, it has two methods, as you can see CMD and secure.

Figure 14.5.3 Methods available in Unix

If you create an object of the type of Linux, it will have three methods, two methods which it got
from its parent CMD and secure, and one method which is created for itself free.

Figure 14.5.4 Methods available in Linux

Here what has happened is that Linux has got all the features of Unix as a parent class.
This is inheritance in the most simplistic format. You can have multiple inheritances; you can
have a multi-level inheritance.

You might also like