The author | HIMANSHI SINGH compile | source of vitamin k | Analytics Vidhya
introduce
While learning object-oriented programming, I decided to delve into its history and found it fascinating. The term “object Oriented programming” (OOP) was coined by Alan Kay in graduate school in 1966.
Simula was the first programming language to feature object-oriented programming. It was developed in 1967 to make simulation programs where the most important information is called objects.
Although OOPS has been on the market since the early 1960s, OOPS began to grow in the 1990s thanks to C++.
In addition, this programming technique has been adopted by various programming languages including Python, and its applications are almost everywhere, such as real-time systems, artificial intelligence, expert systems, CS systems, object-oriented databases, and so on.
So, in this article, I’ll explain the basic concepts of object-oriented programming in Python.
directory
-
What is object-oriented programming?
-
Object Oriented Programming (OOP) vs. Procedure Oriented Programming (POP)
-
The main concept of OOPs
- What is a class?
- Object and object instantiation
- Class method
- Inheritance in Python classes
- encapsulation
- polymorphism
- Data abstraction
What is object-oriented programming?
Object Oriented programming (OOP) is about creating “objects”. An object is a set of interrelated variables and functions. These variables are usually called the properties of the object, and the functions are called the behavior of the object. These objects provide a better, cleaner structure for the program.
For example, a car could be an object. If we think of the car as an object, its properties are — color, model, price, brand, etc., and its behavior/function is speed up, slow down, shift gear.
Another example — if we think of a dog as an object, its attributes are — its color, breed, name, weight, etc., and its behavior/function is walking, barking, playing, etc.
Object-oriented programming is famous for its implementation of objects, hiding, inheritance and other real entities in programming. It makes visualization easier because it is close to real-world scenes.
Object Oriented Programming (OOP) vs. Procedure Oriented Programming (POP)
The basic difference between OOP and procedural programming is this
-
One way to think about POP is the way you make lemonade. The process of making lemonade involves — first taking water as needed, then adding sugar to the water, then adding lemon juice to the mixture, and finally mixing the whole solution. So your lemonade is ready. Similarly, POP requires a certain amount of steps. A program consists of functions. This means that in the POP method, the program is divided into task-specific functions. These functions are arranged in a particular order, and the control of the program takes place in that order.
-
OOP programs are made up of objects. Object-oriented methods divide programs into objects. These objects are entities that bind together the properties and behavior of real-world objects.
-
POP is only good for small tasks. Because as the length of the program increases, so does the complexity of the code. It turns out to be a net of functions. Moreover, it becomes difficult to debug. OOP solves this problem by making the structure clearer and less complex. It allows code to be reused as inheritance.
-
Another important point is that in procedural programming, all functions have access to all data, which means a lack of security. Suppose you want to protect credentials or any other critical information from around the world. Then programmatic methods don’t give you that kind of security. Because this OOP helps you implement an amazing feature called encapsulation, which allows us to hide data. Don’t worry, I’ll cover this and other concepts of object-oriented programming in more detail later in this article. For now, just understand that OOP supports security, POP does not.
-
Programming languages such as C, Pascal, and Basic use procedural methods, while Java, Python, JavaScript, PHP, Scala, and C++ are the main languages providing object-oriented methods.
The main concept of OOPs
In this section, we’ll delve into the basic concepts of OOP. We will discuss the following topics
-
class
-
object
-
methods
-
inheritance
-
encapsulation
-
polymorphism
-
Data abstraction
What is a class?
The straightforward answer to this question is that a class is a collection of objects. Unlike raw data structures, classes are user-defined data structures. They make code more manageable.
Let’s see how to define the following class
class class_name:
class body
Copy the code
We use the keyword “class” to define a class after the class name and semicolon. After using indentation, we consider everything that has indentation. To make this easier to understand, let’s look at an example.
Take car showrooms for example. You want to store the details of each vehicle. Let’s first define a class
class Car:
pass
Copy the code
In this way!
Note: I’ve replaced its body with a pass statement, because the main purpose is to show how to define a class, not what it should contain.
Before going into details, it’s important to understand objects and instantiations.
2. Objects and object instantiation
When we define a class, only a description or blueprint of the object is created, and there is no memory allocation in the process. Object instances have memory allocation, which contains real data or information.
Instantiation is creating an instance of a class. Let’s create an object of the class defined above –
obj1 = Car()
Copy the code
This creates an object instance. Note that you can change the object name as you choose.
Try printing this object
print(obj1)
Copy the code
Because our class is empty, it returns the address of the stored object, 0x7FC5e677b6d8
Before continuing, you need to understand the class constructors.
Class constructor
So far we have an empty car and it’s time to fill our class with car features. The job of a class constructor is to assign values to the class’s data members when the class’s objects are created.
A car can have different attributes such as name, color, model, make, engine power, weight, price, etc. We will select only a few of them for ease of understanding.
class Car:
def __init__(self, name, color) :
self.name = name
self.color = color
Copy the code
Therefore, the attributes of CAR or any other object must be in a method we call **__init__()**. This method is also called the constructor method. The constructor method is called every time an object of the class is constructed.
Now, let’s discuss the arguments to the **__init__()** method. So, the first argument to this method must be self. And then there are the remaining parameters
The two statements in the constructor method are
- self.name = name
- self.color = color:
This creates new properties, name and color, and then assigns the value of the parameter to them. The “self” keyword represents an instance of the class. By using the “self” keyword, we can access the attributes and methods of the class. It is useful in method definition and variable initialization. “Self” is used explicitly each time a method is defined.
Note: You can also create properties outside of this method. But these attributes are common to the entire class and must be assigned values.
Assuming that all cars in your showroom are Sedan, rather than specifying it over and over again, you can fix the value of car_type to Sedan by creating an attribute.
class Car:
car_type = "Sedan" # class attribute
def __init__(self, name, color) :
self.name = name # instance attributes
self.color = color # instance attributes
Copy the code
In this case, instance properties refer to the properties in the constructor method, in this case self.name and self.color. Class attributes are attributes outside the constructor method, in this case car_type.
3. The class methods
So far, we’ve added the car properties. Now it’s time to add some behavior. Methods are the functions we use to describe the behavior of an object. They are also defined in the class. Look at the code below
class Car:
car_type = "Sedan"
def __init__(self, name, mileage) :
self.name = name
self.mileage = mileage
def description(self) :
return f"The {self.name} car gives the mileage of {self.mileage}km/l"
def max_speed(self, speed) :
return f"The {self.name} runs at the maximum speed of {speed}km/hr"
Copy the code
Methods defined in a class (as opposed to constructor methods) are called instance methods. In addition, there are two instance methods, description() and max_speed().
- Description () – This method returns a string containing a description of the car, such as its name and mileage. This method has no additional parameters. This method is using instance properties.
- Max_speed () – This method takes an additional argument and returns a string showing the name of the vehicle and its speed.
Notice that the additional parameter speed does not use the “self” keyword. Since speed is not an instance variable, we do not prefix it with the self keyword. Let’s create an object for the class described above.
obj2 = Car("Honda City".24.1)
print(obj2.description())
print(obj2.max_speed(150))
Copy the code
All we do is create an object of class CAR and pass the required parameters. To use object_name.method_name().
The description() method has no additional arguments, so no arguments are passed when it is called.
The max_speed() method has an additional parameter, so we pass one when we call it.
Note: Three important things to remember
-
You can create any number of objects of a class.
-
If the method requires n arguments and you do not pass the same number of arguments, an error will occur.
-
The order of arguments is important.
Let’s look at them one by one
- Create multiple objects of a class
class Car:
def __init__(self, name, mileage) :
self.name = name
self.mileage = mileage
def max_speed(self, speed) :
return f"The {self.name} runs at the maximum speed of {speed}km/hr"
Copy the code
Honda = Car("Honda City".21.4)
print(Honda.max_speed(150))
Skoda = Car("Skoda Octavia".13)
print(Skoda.max_speed(210))
Copy the code
- Wrong number of arguments
class Car:
def __init__(self, name, mileage) :
self.name = name
self.mileage = mileage
Copy the code
Honda = Car("Honda City")
print(Honda)
Copy the code
We get this error because we didn’t provide the second argument.
- Parameters of the order
class Car:
def __init__(self, name, mileage) :
self.name = name
self.mileage = mileage
def description(self) :
return f"The {self.name} car gives the mileage of {self.mileage}km/l"
Copy the code
Honda = Car(24.1."Honda City")
print(Honda.description())
Copy the code
Confused! Because we changed the order of the argument.
Today, object-oriented programming has four basic concepts: inheritance, encapsulation, polymorphism, and data abstraction. To understand OOPs, it’s important to understand all of this. So far, we’ve covered the basics of object-oriented programming, let’s dig deeper.
4. Inheritance in Python classes
Inheritance is the process by which one class inherits the properties and methods of another class. The inherited class is called a parent class. A class that inherits attributes from a parent class is a subclass.
Interestingly, subclasses can have their own properties and methods in addition to the inherited properties and methods.
How do I inherit from a parent class? Use the following syntax:
class parent_class:
body of parent class
class child_class( parent_class) :
body of child class
Copy the code
Let’s look at the implementation
class Car: # the parent class
def __init__(self, name, mileage) :
self.name = name
self.mileage = mileage
def description(self) :
return f"The {self.name} car gives the mileage of {self.mileage}km/l"
class BMW(Car) : # subclass
pass
class Audi(Car) : # subclass
def audi_desc(self) :
return "This is the description method of class Audi."
Copy the code
obj1 = BMW("BMW 7-series".39.53)
print(obj1.description())
obj2 = Audi("Audi A8 L".14)
print(obj2.description())
print(obj2.audi_desc())
Copy the code
We created two subclasses, “BMW” and “Audi,” that inherit the methods and attributes of the parent class “Car.” We do not provide additional features and functions in the BMW class. And an additional method within Audi.
Notice how the instance method description() of the parent class is accessed by objects of the subclass with the help of obj1.description() and obj2.description(). Additionally, a separate method of the Audi class can be accessed using obj2.audi_desc ().
5. Packaging
As I mentioned at the beginning of this article, encapsulation is one way to ensure security. Basically, it hides the data from outsiders. For example, if we want to keep certain values from being accessed by customers or anyone else without authorization, encapsulation is the way to ensure this.
You can declare a protected method or property by using an underscore (_) before the name of the method or property. For example self._name or def _method(); Both lines indicate that properties and methods are protected and should not be used outside of class and subclass access, but can be accessed by class methods and objects.
Python simply uses’ _ ‘as a coding convention to tell you that you should use these properties/methods within the scope of your class. You can still access protected variables and methods as usual.
Now, to actually prevent access to properties/methods from outside the scope of the class, you can use “private members.” To declare an attribute/method as a private member, use a double underscore (__) in the prefix. For example — self.__name or def __method(); Both lines indicate that properties and methods are private and cannot be accessed from outside the class.
class car:
def __init__(self, name, mileage) :
self._name = name # Protected properties
self.mileage = mileage
def description(self) :
return f"The {self._name} car gives the mileage of {self.mileage}km/l"
Copy the code
obj = car("BMW 7-series".39.53)
Access protected variables through class methods
print(obj.description())
Access protected variables directly from the outside
print(obj._name)
print(obj.mileage)
Copy the code
Notice how we access protected variables without any errors. Obviously, access to variables is still public. Let’s see how encapsulation works. Okay
class Car:
def __init__(self, name, mileage) :
self.__name = name # private variables
self.mileage = mileage
def description(self) :
return f"The {self.__name} car gives the mileage of {self.mileage}km/l"
Copy the code
obj = Car("BMW 7-series".39.53)
Access private variables through class methods
print(obj.description())
Access private variables directly from the outside
print(obj.mileage)
print(obj.__name)
Copy the code
We encountered no errors when we tried to access private variables using the description() method. But when we try to access private variables directly outside the class, Python gives an error declaring that the car object has no attribute ”__name’.
You can still access the property directly using its decorated name. Name Mangling (named modification) is a mechanism for accessing class members externally. The Python interpreter overwrites any identifier with “__var” to “_ClassName__var”. With this you can access class members externally.
class Car:
def __init__(self, name, mileage) :
self.__name = name # private variables
self.mileage = mileage
def description(self) :
return f"The {self.__name} car gives the mileage of {self.mileage}km/l"
Copy the code
obj = Car("BMW 7-series".39.53)
Access private variables through class methods
print(obj.description())
Access private variables directly from the outside
print(obj.mileage)
print(obj._car__name) # name modifier
Copy the code
Note that this rule is designed to handle certain situations, such as in the debugger. It is not recommended for normal programming
6. Polymorphism
Polymorphism is a Greek word. If we break down the term Polymorphism, we get “poly” and “morph” forms. So polymorphism means there are many forms. In OOP, it refers to a function with the same name but different functionality.
class Audi:
def description(self) :
print("This the description function of class AUDI.")
class BMW:
def description(self) :
print("This the description function of class BMW.")
Copy the code
audi = Audi()
bmw = BMW()
for car in (audi,bmw):
car.description()
Copy the code
When a function is called with the object audi, the function of the audi class is called. When a function is called with the object BMW, the function of the BMW class is called.
7. Data abstraction
We use abstractions to hide the internal details or implementation of a function and only show its functionality. It’s similar to knowing how to drive a car without knowing how it works, or knowing how to turn a light on or off with a switch but not knowing what’s going on behind the socket.
Any class with at least one abstract function is an abstract class. To create an abstract class first, you need to import the ABC class from the ABC module. This allows you to create abstract methods in it. ABC stands for abstract base class.
from abc import ABC
class abs_class(ABC) :
Body of the class
Copy the code
Importantly, you cannot create instance objects for abstract classes. For example –
from abc import ABC, abstractmethod
class Car(ABC) :
def __init__(self,name) :
self.name = name
@abstractmethod
def price(self,x) :
pass
Copy the code
obj = Car("Honda City")
Copy the code
The question now is how exactly we use this abstraction. The answer is to use inheritance.
from abc import ABC, abstractmethod
class Car(ABC) :
def __init__(self,name) :
self.name = name
def description(self) :
print("This the description function of class car.")
@abstractmethod
def price(self,x) :
pass
class new(Car) :
def price(self,x) :
print(f"The {self.name}'s price is {x} lakhs.")
Copy the code
obj = new("Honda City")
obj.description()
obj.price(25)
Copy the code
Car is an abstract class inherited from the ABC class of the ABC module. Notice that I have an abstract method (price()) and a concrete method (description()) in the abstract class. This is because abstract classes can contain functions of both types, while ordinary classes cannot. Another class that inherits from this abstract class is New. The price() method of new is where we override the price method of the abstract class Car.
After the user creates an object from the new() class and calls the price() method, the definition of the price method in the new() class comes into play. These definitions are hidden from the user. Abstract methods simply provide a declaration. Subclass definitions need to be provided.
However, when the description() method is called for an object of the new() class (that is, obj), the description() method of Car is called because it is not abstract.
At the end
In summary, in this article, I introduced you to the basic concepts of object-oriented programming in Python. So now you know OOPs and the basic concept.
The original link: www.analyticsvidhya.com/blog/2020/0…
Welcome to panchuangai blog: panchuang.net/
Sklearn123.com/
Welcome to docs.panchuang.net/