Python – OOP

What is OOP?

Object-oriented programming has some advantages over other design patterns. Development is faster and cheaper, with better software maintainability. This, in turn, leads to higher-quality software, which is also extensible with new methods and attributes. The learning curve is, however, steeper. The concept may be too complex for beginners. Computationally, OOP software is slower, and uses more memory since more lines of code have to be written.

Python is a multi-paradigm programming language. It supports different programming approaches including OOP.

An object has two characteristics:

  • attributes
  • behavior

OOP works with classes and objects. A class is a blueprint for the object. An object (instance) is an instantiation of a class. When class is defined, only the description for the object is defined. Therefore, no memory or storage is allocated.

class User():
    name = str
    age = int
    admin_type = "ADMIN"
    user_type = "USER"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        return self.name

Inheritance

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).

class User():
    name = str
    age = int
    admin_type = "ADMIN"
    user_type = "USER"

    def __init__(self, name, age):
        self.name = name
        self.age = age

class Manager(user.User):

    def __init__(self, name, age):
        # call super() function
        super().__init__(name, age)
        print("Manager is ready")

    #inheritance
    man = Manager("Laulau",23)
    print(man.get_name())

# output
Laulau

Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _ or double __.

class Manager(user.User):

    def __init__(self, name, age, active):
        # call super() function
        super().__init__(name, age)
        self._active = True
        print("Manager is ready")

# OOP - inheritance, encapsulation
man = Manager("Laulau",23, False)
print(man.is_active()

# output
False

Polymorphism

Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).

Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism.

class Manager(user.User):

    def __init__(self, name, age, active):
        # call super() function
        super().__init__(name, age)
        self._active = True
        print("Manager is ready")

    def is_active(self):
        return self._active

class CTO(user.User):

    def __init__(self, name, age, active):
        # call super() function
        super().__init__(name, age)
        self._active = True
        print("Manager is ready")

    def is_active(self):
        return self._active

def print_user(man):
    print(man.__dict__)
    print(man.is_active())

man = Manager("Laulau",23, False)

cto = CTO("Laulau",23, False)

print_user(man)
print_user(cto)

# output
{'name': 'Laulau', 'age': 23, '_active': True}
True
{'name': 'Laulau', 'age': 23, '_active': True}
True

 

Key take aways

  • Object-Oriented Programming makes the program easy to understand as well as efficient.
  • Since the class is sharable, the code can be reused.
  • Data is safe and secure with data abstraction.
  • Polymorphism allows the same interface for different objects, so programmers can write efficient code.

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.