Cracking FAANG companies interviews with a few months of preparation
Learn Advanced Data Structures, Algorithms & System Design
Online live classes from 4 to 7 months programs
Get job assistance after course completion
Download Course Brochure
Programming is the process of creating and executing a computer programme to achieve a given computing result or execute a specific task. For instance, we create a calculator that can execute various arithmetic operations. When we need to interface with a computer and direct it to perform certain activities, we need to use programming.
There are many other forms of programming in 2024, but object-oriented programming is the most popular. Many large corporations, like Google, Microsoft, Netflix, Facebook, and others, use it.
So there you have it: everything you need to know about Python OOPs in 2024. Python OOPs come in handy when working with real-time data. Following a solid comprehension of Python OOPs, having a basic understanding of how to become a Software Developer is critical.
So, let’s dive deep into the surplus of useful Python OOPs questions.
Object Oriented Programming (OOP) is a form of programming that uses "objects" to represent data and methods. It's also a method for writing clean, reusable code rather than unnecessary code. The programme is broken down into individual objects or multiple mini-programs. Each every object represents a separate element of the application, with its own logic and data to connect with.
Class, Object, Method, Inheritance, Polymorphism, Data Abstraction, and Encapsulation are all major OOP (object-oriented programming) concepts in Python.
Python's Object Oriented Programming (OOP) is similar to those of other languages. The essential notions are the same, but the syntax is different.
We still use the following concepts: • Classes and objects • Inheritance • Encapsulation • Polymorphism • Abstraction
The mentioned concepts are also important to classic OOP. In Python, the term class is used to declare a class.. Objects are the instances of a class in the same way.
A class is a group of objects, or a blueprint of objects, that defines their common features and behaviour. Now the question is, how do you go about doing that?
It logically organises the data in such a way that code reuse is made simple. Consider an office where 'employee' is a class and all the characteristics associated with it, such as 'emp name,' 'emp age,' 'emp salary,' and 'emp id,' are objects in Python. Let's look at how to instantiate a class and an object from a coding standpoint.
Example: class classEg(): // classEg is the name of the class
Objects:
A class's instance is an object. It's a thing with a state and a personality. In a nutshell, it is a class instance that has access to data.
Syntax: Syntax: obj = classEg(); Here obj is the “object “ of classEg.
In programming, OOPs provides clarity. It solves complicated problems with flexibility and simplicity. Because the inheritance notion helps to decrease code repetition, reusing code is simple. Encapsulation binds data and code together. Data hiding mechanisms are available in OOPs, allowing private data to be kept while maintaining secrecy. Problems can be broken down into smaller chunks, making them easier to tackle. Polymorphism is a flexible notion since a single entity can have numerous forms.
In Python, abstraction is defined as a method of dealing with complexity by hiding superfluous data from the user. Object-oriented programming (OOP) languages have this as one of their key notions. This allows the user to build on top of the offered abstraction and design even more complex logic without having to understand or even consider all of the hidden background/back-end complexity.
In Python, we can create abstraction by including/using abstract classes and functions in our code.
In Python, polymorphism refers to an object's capacity to take several forms. Polymorphism, in simple terms, allows us to do the same activity in multiple ways.
When Jessa is at work, for example, she pretends to be an employee. When she's at home, however, she acts like a wife. She also shows herself in a variety of ways depending on where she is. As a result, the same person assumes various identities depending on the circumstances.
A method can treat objects differently depending on the class type or data type in polymorphism. Let's look at some simple instances to help you understand.
Example:
The built-in function len() calculates the length of an object depending upon its type. If an object is a string, it returns the count of characters, and If an object is a list, it returns the count of items in a list.
Polymorphism is used in Python for a variety of purposes, including Duck Typing, Operator and Method overloading, and Method overriding, as it is in other programming languages such as Java and C++. Overloading and overriding are two methods for achieving this polymorphism.
Overloading
Overloading can be categorised into two types.
• Operator Overloading
• Method Overloading
Operator overloading occurs when an operator can be used in ways other than those specified in its predefined specification.
>>>print(2*7) 14 >>>print("a"*3) aaa Try it Yourself
The multiplication operator multiplied two numbers in the first example; however, because multiplication of a string and an integer is not possible, the character is displayed three times twice in the second. As a result, it demonstrates how a single operator can be utilised in a number of different ways.
Method Overloading
Overloading a method is when a class contains multiple methods with the same name but perhaps different parameters. While Python does not support method overloading by default, there are a number of workarounds. While method overloading is feasible, it is only possible to use the most recently declared methods.
For example:
Assume we have a class A, and we have a function display with a function constructor self and arguments with the default values None and None within the class. Then, despite the knowledge that it would display None and None because we put default values in the function area, I created an object and called the function with the object obj.show, but I didn't offer any parameters.
class A: def show(self, a=None, b=None): print(a,b) obj=A() obj.show() Try it Yourself
Duck Typing
Polymorphism is a term used to describe the concept of duck typing. Duck typing comes from an adage that states that anything that walks, quacks, and swims like a duck is referred to as a duck, regardless of the item. In simple terms, it means that if anything behaves similarly to another, it will be classified as a member of that category.
Method Overriding
The technique of altering a base class using the methods and parameters of a derived class is known as method overriding.
For Example:
class Vehicle: def run(self): print("Saves Energy") class EV(Vehicle): pass ev = EV() ev.run() Try it Yourself
As a result, because the derived class lacks a method, when the function is called, the output will show the method of the base class.
The object-oriented paradigm relies heavily on inheritance. Because we can use an existing class to construct a new class rather than starting from scratch, inheritance allows us to reuse code.
A simple example of inheritance in Python is shown below.
class Parent(): def first(self): print('first function') class Child(Parent): def second(self): print('second function') ob = Child() ob.first() ob.second() Try it Yourself
There are four types of inheritance in Python, depending on the number of child and parent classes involved.
Single Inheritance
When only one parent class is inherited by a child class.
class Parent: def func1(self): print("this is function one") class Child(Parent): def func2(self): print(" this is function 2 ") ob = Child() ob.func1() ob.func2() Try it Yourself
Multiple Inheritance
When more than one parent class is inherited by a child class.
class Parent: def func1(self): print("this is function 1") class Parent2: def func2(self): print("this is function 2") class Child(Parent , Parent2): def func3(self): print("this is function 3") ob = Child() ob.func1() ob.func2() ob.func3() Try it Yourself
Multilevel Inheritance
When a kid class adopts another child class as a parent class.
class Parent: def func1(self): print("this is function 1") class Child(Parent): def func2(self): print("this is function 2") class Child2(Child): def func3("this is function 3") ob = Child2() ob.func1() ob.func2() ob.func3() Try it Yourself
Hierarchical Inheritance
Multiple inheritance from the same base or parent class occurs in hierarchical inheritance.
class Parent: def func1(self): print("this is function 1") class Child(Parent): def func2(self): print("this is function 2") class Child2(Parent): def func3(self): print("this is function 3") ob = Child() ob1 = Child2() ob.func1() ob.func2() Try it Yourself
Hybrid Inheritance
Multiple inheritance occurs in a single programme with hybrid inheritance.
class Parent: def func1(self): print("this is function one") class Child(Parent): def func2(self): print("this is function 2") class Child1(Parent): def func3(self): print(" this is function 3"): class Child3(Parent , Child1): def func4(self): print(" this is function 4") ob = Child3() ob.func1() Try it Yourself
When an object is formed, the function constructor method is invoked. The class defines this method, which can be used to set up basic variables. The class function constructor is invoked four times if you generate four objects. Every class has a function constructor, but it isn't necessary to define it explicitly.
The function init is used to generate the constructor. We use the self keyword as a parameter, which refers to itself (the object).
We set up two variables in the constructor: legs and arms. In the context of object-oriented programming, variables are sometimes referred to as properties. We create one object (bob), and its variables are set only by creating it.
class Human: def __init__(self): self.legs = 2 self.arms = 2 bob = Human() print(bob.legs) Try it Yourself
The constructors in C++ and Java are identical to the __init__ method. Constructors are used to set the state of an object. Constructors are responsible for initialising (assigning values) the data members of a class when an object of that class is created. A constructor, like methods, includes a collection of statements (i.e. instructions) that are performed when an object is created. It is called whenever a class object is instantiated. The method can be used to do any type of object initialization.
class Person: # init method or constructor def __init__(self, name): self.name = name # Sample Method def say_hi(self): print('Hello, my name is', self.name) p = Person('Rama') p.say_hi() Try it Yourself
When an object is destroyed, destructors are called. Destructors aren't as important in Python as they are in C++ because Python contains a garbage collector that handles memory management for you.
The __del__() method is known as a destructor method in Python. When all references to an object have been destroyed, i.e. when an object is garbage collected, this method is invoked.
The destructor was invoked after the programme finished or after all references to the object were erased, i.e. when the reference count reached zero, rather than when the object was removed from scope.
class Employee: # Initializing def __init__(self): print('Employee created.') # Deleting (Calling destructor) def __del__(self): print('Destructor called, Employee deleted.') obj = Employee() del obj Try it Yourself
The class instance is represented by self. The "self" keyword in Python allows us to access the class's attributes and methods. It connects the attributes to the arguments. You'll have to use self because Python doesn't utilise the @ notation to refer to instance attributes. Python chose to implement methods in such a way that the instance to which the method belongs is automatically supplied, but not automatically received: the first parameter of methods is the instance on which the method is called.
Current Object is always pointing by Self.
One of the core principles in object-oriented programming is encapsulation (OOP). It covers the notion of data wrapping as well as methods for working with data as a single unit. By prohibiting direct access to variables and procedures, this prevents data from being unintentionally modified. An object's variable can only be altered by an object's method to prevent unintentional changes. Private variables are the name given to these variables.
⮞ Protected Members
Protected members (in C++ and JAVA) are class members that can only be accessible from within the class and its subclasses and cannot be accessed from outside the class. To do so with Python, simply use the standard of prefixing the member's name with a single underscore "_"
⮞ Private members
Private members are similar to protected members, with the exception that class members declared private should not be accessed by anybody outside of the class, including any base classes. Private instance variables, which may only be accessed within a class, do not exist in Python.
A blueprint for other classes can be regarded an abstract class. It enables you to define a set of methods that must be implemented in any child classes that are derived from the abstract class. A class with one or more abstract methods is called an abstract class. The term "abstract method" refers to a method that has a declaration but no implementation. We employ an abstract class for designing huge functional units. We utilise an abstract class to provide a standard interface for diverse implementations of a component.
Python does not provide abstract classes by default. ABC is the name of the Python module that provides the foundation for defining Abstract Base Classes (ABC). ABC works by registering concrete classes as abstract base implementations and then decorating base class methods as abstract. When a method is equipped with the @abstractmethod keyword, it becomes abstract.
# Python program showing # abstract base class work from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def noofsides(self): pass class Triangle(Polygon): # overriding abstract method def noofsides(self): print("I have 3 sides") class Pentagon(Polygon): # overriding abstract method def noofsides(self): print("I have 5 sides") class Hexagon(Polygon): # overriding abstract method def noofsides(self): print("I have 6 sides") class Quadrilateral(Polygon): # overriding abstract method def noofsides(self): print("I have 4 sides") # Driver code R = Triangle() R.noofsides() K = Quadrilateral() K.noofsides() R = Pentagon() R.noofsides() K = Hexagon() K.noofsides() Try it Yourself
Python's super() method makes class inheritance easier to maintain and extend. The function returns a temporary object that can be used to refer to a parent class using the super keyword.
The super() function is useful in two situations:
• To avoid having to use the super (parent) class directly. • To make multiple inheritances possible.
class person: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname def fullname(self): print(firstname, ' ', lastname) class student(person): def __init__(self, firstname, lastname, grade): self.grade = grade super().__init__(firstname, lastname) # calling base constructor def display_details(): super().fullname() # calling base class method print('Grade ', self.grade) std = student('Eliza', 'Beth', '10') std.display_details() Try it Yourself
In the example above, super(). init (firstname, lastname) in the student class's init function calls the base class person's init method and passes parameters to it. Similarly, super().fullname() invokes the person.fullname() method. super().fullname() is another name for super() (student, self). fullname().
In plain text or other data streams, a delimiter is a sequence of one or more characters that defines the boundary between different, independent areas. The comma character, which works as a field delimiter in a sequence of comma-separated data, is an example of a delimiter.
Decorators are a very strong and helpful Python tool because they allow programmers to change the behaviour of a function or class. Decorators allow us to wrap another function in order to expand its behaviour without having to change it permanently. But, before we delve too deeply into the topic of decorators, let us first comprehend a few ideas that will aid us in our research.
Let's have a look at how a decorator function in Python works.
# example of decorator def sampleDecorator(func): def addingFunction(): # some new statments or flow control print("This is the added text to the actual function.") # calling the function func() return addingFunction @sampleDecorator def actualFunction(): print("This is the actual function.") actualFunction() Try it Yourself
In Python, static methods are very similar to class level methods, with the exception that a static method is bound to a class rather than the objects for that class.
This indicates that a static method for a class can be invoked without the need for an object for that class. This also means that because static methods aren't tied to an object, they can't change its state. Let's look at how to make static methods in Python.
⮞ Using staticmethod()
class Calculator: def addNumbers(x, y): return x + y # create addNumbers static method Calculator.addNumbers = staticmethod(Calculator.addNumbers) print('Product:', Calculator.addNumbers(15, 110)) Try it Yourself
There were no revelations in that area. This approach is controlled because a static method can be created from a class method at any point. Let's have a look at another technique using the same scenario.
⮞ Using @staticmethod
This is a more sophisticated technique of making a static method because we don't have to rely on a statement declaration of a method being a class method and making it static at each location.
class Calculator: # create addNumbers static method @staticmethod def addNumbers(x, y): return x + y print('Product:', Calculator.addNumbers(15, 110)) Try it Yourself
A class method is a method that all objects have access to. Put the class as the first argument when calling a class method.
Class methods are accessible from both instances and the class itself. The procedure is the same in all of them. The variables and methods of the classes can be used by the method.
Add @classmethod before the method definition to make it a classmethod. The class is always passed as a parameter to the method.
A class method is defined in the example below. After that, the class method can be called by the class itself. The class method in this example makes use of the class property name.
class Fruit: name = 'Fruitas' @classmethod def printName(cls): print('The name is:', cls.name) Fruit.printName() Try it Yourself
⮞ A class method, like a static method, does not need the creation of an object.
⮞ A class method varies from a static method in that the static method is unaware of the class's existence. The class is always the parameter in a classmethod.
⮞ Static methods have no knowledge of the class or instance. You might use a function call instead.
⮞ When a class method is called, the class is returned. It is aware of the characteristics and methods of the classes.
Lambda functions in Python are anonymous, which means they don't have a name. The def keyword is used to define a typical Python function, as we already know. In Python, the lambda keyword can also be used to declare an anonymous function.
lambda arguments: expression
# Python code to illustrate cube of a number # showing difference between def() and lambda(). def cube(y): return y*y*y lambda_cube = lambda y: y*y*y # using the normally # defined function print(cube(5)) # using the lambda function print(lambda_cube(5)) Try it Yourself
⮞ Lambda is a one-expression function, whereas Def can hold several expressions.
⮞ Def creates a function and gives it a name so that it can be called later. A function object is created and returned by Lambda.
⮞ A return statement can be used in Def. Return statements aren't allowed in Lambda.
⮞ Lambda can be used within a list or a dictionary.
This page has finally come to an end. With the information on this page and a little practise, you should be able to create your own programmes, and modest projects are really encouraged for increasing your programming skills. It's impossible to learn everything you need to know about programming in only one lesson. Whether you're a seasoned professional developer or a complete novice, programming is a never-ending learning process.
class Dog: def __init__(self, name, age): self.name = name self.age = age
s = "\t\tWelcome\n" print(s.strip())