Python OOP

In Python, object-oriented programming (OOP) is a programming style that fits variables into ‘classes’.

Introduction

So for Python OOP you’ll need two programs: a main program to run your code, and another one that has all your data.

For example, let’s say we want to write a code that says our age this year and our age next year.

In this case I’ll be naming my two programs main.py and aging.py. First, we initialize the variables we need in aging.py. Here’s how to do it-

Writing the Code

Initialization

class Aging_Class:
    def __init__(self,name,ID,age):
        self.name = name
        self.ID = ID
        self.age = age

    def age_next_year(self):
        self.age += 1

In line 1, we initialize the class Aging_Class. The __init__ method is declared within the class and is used to initialize the attributes, name, ID, and age.

The self keyword allows constructed variables to have its own data. Think of the self keyword like it’s a boss. The employees need the boss’s permission to do anything. More on constructing later.

In line 7, we create age_next_year. This subprogram allows the person’s age to increase.

That’s all in aging.py. Now, we start writing code in main.py!

Importing Classes

Since we already have the class in aging.py, here’s how to transfer it over to main.py

from aging import Aging_Class

Constructors

from aging import Aging_Class
next_year = False
family_member_1 = Aging_Class("daphne","001",13)

In line 3, family_member_1 is a variable constructed from the class Aging_Class. The fixed name, ID, and age are daphne, 001, and 13 respectively. We need the self keyword to enter the data, otherwise it won’t work.

Now, we use normal programming to complete the code-

from aging import Aging_Class
next_year = False
family_member_1 = Aging_Class("daphne","001",13)

sentence_1 = family_member_1.name + " " + "is" + " " + str(family_member_1.age) + " " + "this year"
next_year = True

family_member_1.age_next_year()
sentence_2 = "she" + " " + "will be" + " " + str(family_member_1.age) + " " + "next year"

print(sentence_1)
print(sentence_2)

Result

The result-

daphne is 13 this year
she will be 14 next year

Useful Keywords

  1. initialize – provide the starting value of a variable in computer programming
  2. attribute – equivalent to variable in normal programming, a characteristic that can be set to different values
  3. import – when someone transfers digital stuff from one program to another

Conclusion

That’s all! I hope you found this guide useful.

Leave a Reply