Understanding OOP in Python

Understanding OOP in Python


Hey everyone :wave:. Today I will explain what OOP is, what is is used for, and how to use it yourself in Python.

I hope you enjoy!


What is OOP?

OOP stands for Object-Oriented Programming. Wikipedia says:

Object-oriented programming (OOP ) is a programming paradigm based on the concept of objects , which can contain data and code. The data is in the form of fields (often known as attributes or properties ), and the code is in the form of procedures (often known as methods ).

“Many of the most widely used programming languages (such as C++, Java,[3] Python, etc.) are multi-paradigm and they support object-oriented programming to a greater or lesser degree, typically in combination with imperative, procedural programming.

Significant object-oriented languages include: Ada, ActionScript, C++, Common Lisp, C#, Dart, Eiffel, Fortran 2003, Haxe, Java,[3] JavaScript, Kotlin, logo, MATLAB, Objective-C, Object Pascal, Perl, PHP, Python, R, Raku, Ruby, Scala, SIMSCRIPT, Simula, Smalltalk, Swift, Vala and Visual Basic.NET.”


What is OOP used for?

coursera states that:

“Object-oriented programming (OOP) is a way of thinking about and organizing code for maximum reusability. With this type of programming, a program comprises objects that can interact with the user, other objects, or other programs. This makes programs more efficient and easier to understand.”

Pros of OOP:

  • We can build the programs from standard working modules that communicate with one another, rather than having to start writing the code from scratch which leads to saving of development time and higher productivity,
  • OOP language allows to break the program into the bit-sized problems that can be solved easily (one object at a time).
  • The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost.
  • OOP systems can be easily upgraded from small to large systems.
  • It is possible that multiple instances of objects co-exist without any interference,
  • It is very easy to partition the work in a project based on objects.
  • It is possible to map the objects in problem domain to those in the program.
  • The principle of data hiding helps the programmer to build secure programs which cannot be invaded by the code in other parts of the program.
  • By using inheritance, we can eliminate redundant code and extend the use of existing classes.
  • Message passing techniques is used for communication between objects which makes the interface descriptions with external systems much simpler.
  • The data-centered design approach enables us to capture more details of model in an implementable form.

Cons of OOP:

  • The length of the programmes developed using OOP language is much larger than the procedural approach. Since the program becomes larger in size, it requires more time to be executed that leads to slower execution of the program.
  • We can not apply OOP everywhere as it is not a universal language. It is applied only when it is required. It is not suitable for all types of problems.
  • Programmers need to have brilliant designing skill and programming skill along with proper planning because using OOP is little bit tricky.
  • OOPs take time to get used to it. The thought process involved in object-oriented programming may not be natural for some people.
  • Everything is treated as object in OOP so before applying it we need to have excellent thinking in terms of objects.

Places that OOP is used within Python would be things like:

  • Web and app development
  • GUI
  • Game development
  • Network Programming
  • Operating system
  • Testing and test automation

As you can see there are many benefits to using OOP with some disadvantages you would have to get used to.


How can we use OOP?

Now that we learned what OOP is and how we can use it, you probably want to learn how exactly we do this.
So in this tutorial we are using Python to learn OOP.

In Python to start using OOP we can create a class like this.

class ClassName():

Classes are places in which we can create objects. A class is basically a blueprint telling how we create these objects.

Note: In this tutorial I am going to create a class that makes a monster from some arguments.

So now we are going to create some arguments, but they aren’t done in the way you make functions.

class Monster(health: int, damage: int, _type: str):

To create arguments we need to use an __init__ method, which initializes our new object. When we create this function one of the arguments always has self, as this allows you to pass variables around the class easily while having a variable only for that object.

def __init__(self, name: str, health: int, damage: int, level: int):
    self.name = name
    self.health = health
    self.damage = damage
    self.level = level

Note: Methods need to be indented inside the class.

Now that we have our __init__ function and we know what it’s for let’s create another important function that we can change in many ways to fit our purpose. The function we are going to use now is __str__. The __str__ function says what we print out when we call our object. In my example I can do this something like this:

def __str__(self):
    return f"""
{self.name}:

  HEALTH: {self.health}
  DMG: {self.damage}
  LEVEL: {self.level}
"""

Note: I use self as the argument so I can access the variables from the __init__ function. We also use return instead of print to make sure our stuff gets printed correctly

Now that we have our basic functions that are needed we can add functionality to our Class. In my example I am going to save my monster data to a JSON file.

def save_data(self):
    data = {
        {self.name}: {
            {
                "HEALTH": {self.health},
                "DMG": {self.damage},
                "LEVEL": {self.level}
            }
        }
    }
    with open('monsterData.json', 'w') as json_file:
        json.dump(data, json_file)

Note: In this example I did not show importing JSON but still should be done if you are importing anything, like with normal programming import at the top of the file
And then to call our function we can add them to our __init__ function.

def __init__(self, name: str, health: int, damage: int, level: int):
    # rest of code
    self.save_data()

Note: when calling a function in a Class make sure to put self. in front of it

Now we are done with our Class code we can move on to making our object. If you want to do this in a separate file you can just make sure to import your Class file correctly.

We first want to initialize or curate our object, we can set it up with a variable like so:

monster = Monster("Gecko", 15, 10, 7)

Then we can print it out by using the print function and our object variable:

print(monster)

Now we can change the health variable of the object and then save the monster data to a file.

monster.health -= 1 # reducing the health variable of the monster object by 1
monster.save_data() # saving data

Note: To access the functions and variables of an object, you need to write the name of the object, then ., followed by the name of the variable or function.


And that’s it, we successfully learned OOP and created with OOP in Python.
I hope you enjoyed and found this tutorial helpful!

Rate how good/helpful the tutorial was (1 Being Terrible - 10 Being Really Good/Helpful)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
0 voters

(If you didn’t think it was good leave a reply saying why so I can improve it and my future tutorials)

Should I Create an OOP Tutorial Like This for JavaScript?
  • Yes
  • No
0 voters

Made with :heart: by @SalladShooter

6 Likes

I think that it is also necessary to show how to change the internal variables of an object using class functions or through the object itself. What do you think about it?

The same as in the __init__ method, though?

I mean to show in the manual the change of an object variable for example like this:

monster.monster_health -= 1

or this:

def damage(x):
    self.monster_health -= x
1 Like

Well it’s a wiki so you can edit it and add that.

Thanks a lot for sharing it here.
Here is the application of OOP in Python.

  1. Web and app development
  2. GUI
  3. Game development
  4. Network Programming
  5. Operating system
  6. Testing and test automation
    Thanks
2 Likes

In short, OOP is applied everywhere.

1 Like