top of page
Writer's pictureNazeeruddin

OOPs in Python - Creating classes and objects

Updated: Jan 28, 2023

Object Oriented Programming or known as OOPs is a programming paradigm that consists of concepts like abstraction, encapsulation inheritance and polymorphism.


Using the concepts of OOPs is a highly efficient way of writing a program.


Why OOP?

With the help of OOPs, we can achieve the code reusability, easy maintenance, and easy to design the complex applications. OOPs is much more powerful than using functions.


Terminology:

Class is a logical construction, or it is called as blueprint of object. Memory will not be allocated by defining the class. for example, Animal, Bird, Vehicle, Person etc.,


Object is a physical a construction of the class. Memory will be allocated for each object uniquely. for example, Dog, Parrot, Car, Employee etc.,


Attributes are fields defined inside the class, which is providing the state of the object. for example, name, age, salary of an employee object.


Methods defines the behavior of the object; method defines the actions of the object; we can modify the state of the object.


Let's Start:

Defining a class, and object

Employee is class.

emp1, and emp2 are objects. emp1 and emp2 both are allocating unique memory.

Employee(101, "Nazeeruddin", 96000)

  1. Above statement calls __new__(cls) method, which creates and returns the object.

  2. created object passed as an argument to __init__(self)

    • __init__(self) called after object creation

    • __init__(self) functionality is to initialize the object


class method: member function first parameter is 'cls'
instance method: member function first parameter is 'self'
static method: member function first parameter is neither 'cls' nor 'self'

instead of 'cls', and 'self', we can use any name, but we have to stick with guidelines.


class method can access to only class level fields, which are shared among objects, instance method can access both instance and class fields.


Instance fields, defined in __init__ method using 'self' keyword, each object having its own copy of instance fields.

self.eno, self.ename, and self.esal are instance fields.


emp1 object fields are 101, "Nazeeruddin", 96000

emp2 object fields are 102, "Sowmya", 98000


class variables/fields are shared among objects, they can be accessed using 'cls' keyword or class_name.


following code Employee._count is a class variable.

@classmethod decorator defines a class method, it can be called using the class name, for example: Employee.get_count()


  • class method first parameter is 'cls'

  • class method can access only class fields using 'cls' keyword

  • class fields can be accessed from any instance method using the class name. for example: Employee._count


Here, Employee.from_string(...) class method creates an object from a string.

@staticmethod decorator defines a static method, they are not bound to the instance or the class. They are included in class, because they logically belong to the class. usually, static methods are defined as utility classes to perform a group of related tasks.


  • static methods are defined with the @staticmethod decorator

  • static methods can't access instance fields nor class variables.

  • static methods can be accessed by a class name or instance.

Access Modifiers in python


Python uses ‘_’ symbol to determine the access control for a specific data member or a member function of a class. Access specifiers in Python have an important role to play in securing data from unauthorized access and in preventing it from being exploited.


A Class in Python has three types of access modifiers:


  • Public Access Modifier

  • Protected Access Modifier

  • Private Access Modifier

public, and protected fields can be accessed by object, and also, they can be followed, but accessing protected fields by object, or modifying is not recommended.


private fields are not accessible by object, touching the private fields will result in AttributeError.


Encapsulation

Encapsulation is wrapping data and the methods that work on data within one unit. This puts restrictions on accessing data members and methods directly and can prevent the accidental modification of data.


Here account1 object field __balance can be modified by class member function withdraw () only.

Inheritance

Inheritance is a mechanism of reusing and extending existing classes without modifying them, it is producing hierarchical relationships between them.

  • class Developer achieves. code reusability, initializing the Employee details id, and name is handled by the base class only.

  • Employee class added with a new feature add_skills (), without modifying it.

  • Employee and Developer producing the hierarchical relationship, Employee is the base or parent class, and Developer is the derived or child class.

In C++, and Java Programming languages, while creating an instance from derived class, constructors are called automatically from base to derived. But in python we need to call the base class __init__ method explicitly.


Polymorphism

Polymorphism means many forms. one name many forms, or one object behaving as multiple forms.

Here, len () function implemented with multiple forms, to calculate the length of string, and count of items in the list.

Here len(any) function parameter type is 'Any'. you can interpret the above program as...

  • len(name) calls name.__len__()

  • len(skills) calls skills.__len__()

function overloading: a function can be called by passing variable length of arguments.

Method overriding: In class hierarchy derived class methods are having the same signature of the base class method.

Above code can't be interpreted like C++ or Java. Python function calling is neither call by value nor call by reference. It is call by sharing (also known as 'call by object' or 'call by object sharing')


Here mymethod arg type is not Base always, it depends on the object type being passed.

Everything in Python is an object and the assignment operation is just binding a name to an object.

What is Abstraction? How to define an abstract base class?

Abstraction is Hiding the complex or unnecessary details and exposing the essential features is called abstraction.

Abstraction is the designing perspective view.


  • Abstract class can't be instantiated, because it is incomplete class.

  • concrete class, which is providing the implementation of the abstract class, in class hierarchy.


Why Abstract class:

By defining an abstract base class, you can define a common Application Program Interface (API) for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations, such as plugins.

 
Thanks for reading!!!

Your Rating and Review will be appreciated!!

Twitter: @LearnerLandmark

197 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page