Python For Beginners

Python For Beginners

Object Oriented Programming in Python

Now, let’s do something new.

Actually, this is something which usually comes much later, as advanced subjects.

But still, I wanted to present you with an example of where are we going.

Furthermore, it is good to see more real life example at the early stages of learning.

This helps you compare your current learning with a bit more advanced example.

Our first Object Oriented example

We want to take our is_integer_negative function and put it inside of some kind of context.

Also, we want to be able to write similar functions, and keep all of them within a same context.

This is similar to when you want to order pictures in Albums or Folders.

  • You have the same pictures, but they are more logical to access.
  • If you move some albums, all the pictures will move with them (you don’t have to do it one by one)
  • If you share one album, then people can access all the photos there, but not the other albums. You don’t have to worry about sharing photo by photo.
  • And much more things…

Essentially, Object Oriented programming is there to solve the problem of code reuse, sharing among the different parts of software and different developers.

Is there a correct way of writing Object Oriented programs? hmm, is there a correct way of ordering a pictures in Albums?

Joke aside, there are detailed pointers on what should and should not be done.

But essentially, it is related to experience, making mistakes lots of times, and refactoring.

Some vocabulary:

  • Class – a template which usually represents some concept from real world which we program
  • Object – a practical implementation of the class (essentially, it is our template filled in with some real data)
  • Refactoring – writing a code in a better way (essentially, a fancy way to say that you found a way to improve existing code)

Ok, back to what we were doing.

We want to take our function from previous example and turn it into something more advanced, a class.

Take a look at the example below, and as we did in previous examples, retype it in an online Python parser.

class Calculator:
    
    def __init__(self,x):
        self.x = x
        
    def is_integer_negative(self):
        if self.x < 0:
            print('The number you have entered is negative')
        elif self.x == 0:
            print('The number you have entered equals zero')
        else:
            print('The number you have entered is positive')
    
    def is_equal_five(self):
        if self.x == 5:
            print("This number is equal 5")
        else:
            print("This number is not equal 5")
            


johns_calculation = Calculator(5)
johns_calculation.is_integer_negative()
johns_calculation.is_equal_five()

marias_calculation = Calculator(-3)
marias_calculation.is_integer_negative()
marias_calculation.is_equal_five()
calculator example
calculator example

Now, let’s quickly see what is going on here:

  • line 1 – we are making a new class called Calculator
  • line 3 – we are making an __init__ function. We will learn details about this later. For now, just keep in mind that this function is executed when class is called. Here, we can see that class has one parameter “x”. Think of it as of real life calculator. You can enter one number (or more numbers) and then decide what to do with them (multiply, divide, etc.).
  • line 6-12 – our class can have multiple functions, meaning multiple things that can be done. We implemented our function from previous example.
  • line 14-18 – We implemented one more function called “isEqualFive” which checks if the number is equal five.

Ok, so we have a class which can accept one number, X, and then we can execute two functions isIntegerNegative() and isEqualFive() against that number.

Now, in order to use class, first we must create an object.

There are lots of explanation what object is:

  • Object is materialization of class.
  • Class is unique, and objects can be multiplied.

The easiest way to understand is this: When we take a class and add some real values to it, we get object.

Since we can use same class and add lots of different values to it, we can make lots of different objects from a same class.

In our example we made 2 objects:

  • line 22 – we created an object called johnsCalculator
    • john entered number 5 in his calculator
    • john then called isIntegerNegative function
    • john then called isEqualFive function
  • line 26 – we created one more object called mariasCalculator
    • maria entered number -3 in his calculator
    • maria then called isIntegerNegative function
    • maria then called isEqualFive function

These are the results we got.

Can you understand why did we got these messages?

Python Object Oriented Calculator results
Python Object Oriented Calculator results

 

 

One more example of Object Oriented program in Python

Ok, so what do we have here?

  • There is an program, where you should be able to recognize some elements: comments, print function, if-else structure.
  • There are some new commands which you probably see for a first time: class, def, format, etc.

This is completely ok. You don’t have to understand it at this point.

For now, you should open Online Python compiler and type this example there.

Yes, you are provided with screenshot only, so you actually have to type it (no copy-pasting).

Python First Object Oriented Example
Python First Object Oriented Example

When we execute this program, we will get a response in a console.

Python First Object Oriented Example Results
Python First Object Oriented Example Results
  • This response has 4 lines (meaning print function was executed 4 times)
  • First response is telling us “John is 15 years old…”
    • This was created by line 27, where print function did several things.
    • First, print function had a placeholder {} which keeps a place for some information, which will come from memory.
    • This placeholder was filled in by function format
    • Actually, this print has two placeholders {} {}, which were filled by john.name and john.age, values.
      • Now, what is ‘john’ here?
        • ‘john’ is an object, created in a line 24.
        • What is this object created of?
          • john = Student(“John”, 15) – this line of the code tells us to create a object named ‘john’ from a class called Student. Then store “John” and 15 information in this object.
        • How do our object knows what “John” and 15 means?
          • This logic is implemented between lines 16-18, where we clearly say define first argument as name, and second argument as age.

 

 

 

One thought on “Object Oriented Programming in Python”
Leave a Comment