Abstract: Python does not have an access specifier like "private" in java. In addition to strong encapsulation, it supports most of the terms related to "object-oriented" programming languages. Therefore it is not completely object-oriented.
This article is shared from the Huawei Cloud Community " Learn Python from Scratch | Object-Oriented Programming Python: Everything You Need to Know ", the original author: Yuchuan.
Object-oriented programming as a discipline has gained widespread follow among developers. Python, a popular programming language, also follows the object-oriented programming paradigm. It handles the declaration of Python classes and objects that lay the foundation for OOP concepts. This article on "Object-Oriented Python Programming" will take you through the four methods of declaring Python classes, instantiating objects from them, and OOP.
What is object-oriented programming? (OOP concept in Python)
Object-oriented programming is a computer programming method that uses the idea of "objects" to represent data and methods. It is also a way to create clean and reusable code instead of redundant code. The program is divided into independent objects or several small programs. Each individual object represents a different part of the application, and they have their own logic and data to communicate within them.
Now, in order to understand more clearly why we use oops instead of pop, I have listed the differences below.
The difference between object-oriented and process-oriented programming
That's all the difference, go ahead and let us understand Python OOPs Conceots.
What is the Python OOP concept?
The main OOP (Object Oriented Programming) concepts in Python include classes, objects, methods, inheritance, polymorphism, data abstraction, and encapsulation.
That's all the difference is, let us continue to understand classes and objects.
What are classes and objects?
A class is a collection of objects, or you can say that it is a blueprint for objects that define common properties and behaviors. Now the question is, how did you do it?
Well, it logically groups data in a way that makes code reusability easy. I can give you an example in real life-think of an office as "employee" as a class, and all the attributes related to it, such as "emp_name", "emp_age", "emp_salary", "emp_id" as Python In the object. Let us look at how to instantiate a class and an object from a coding perspective.
Classes are defined under the "class" keyword.
example:
class class1(): // class 1 is the name of the class
Note: Python is not case sensitive.
Object:
Objects are instances of classes. It is an entity with state and behavior. In short, it is an instance of a class that can access data.
Syntax: obj = class1()
Here obj is the "object" of class1.
Create objects and classes in python:
example:
class employee():
def __init__(self,name,age,id,salary): //creating a function
self.name = name // self is an instance of a class
self.age = age
self.salary = salary
self.id = id
emp1 = employee("harshit",22,1000,1234) //creating objects
emp2 = employee("arjun",23,2000,2234)
print(emp1.__dict__)//Prints dictionary
Description: ' and'emp2' are objects instantiated for the class'employee'. Here, the word (__dict__) is a "dictionary", which prints all the values of the object'emp1' according to the given parameters (name, age, salary). (__init__) is like a constructor, it will be called whenever an object is created.
I hope that now you will not encounter any problems when dealing with "classes" and "objects" in the future.
With this, let me take you to understand object-oriented programming methods:
Object-oriented programming method:
Object-oriented programming methods involve the following concepts.
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
Let us understand the first concept of inheritance in detail.
inherit:
I have heard from relatives say that "you look like your father/mother". The reason behind this is called "inheritance". In terms of programming, it generally means "inherit or transfer the characteristics of the parent class to the subclass without any modification." The new class is called the derived/subclass, and the class derived from it is called the parent/base class.
Let us understand each subtopic in detail.
Single inheritance:
Single-level inheritance enables derived classes to inherit characteristics from a single parent class.
example:
class employee1()://This is a parent class
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
class childemployee(employee1)://This is a child class
def __init__(self, name, age, salary,id):
self.name = name
self.age = age
self.salary = salary
self.id = id
emp1 = employee1('harshit',22,1000)
print(emp1.age)
Output: 22
explanation:
- I am using the parent class and creating a constructor (__init__), and the class itself is using parameters ('name','age' and'salary') to initialize properties.
- Created a subclass "childemployee", which inherits the properties of the parent class, and finally instantiated the objects "emp1" and "emp2" according to the parameters.
- Finally, I have printed the age of emp1. Well, you can do many things, such as printing the entire dictionary or name or salary.
Multi-level inheritance:
Multi-level inheritance enables a derived class to inherit properties from its direct parent class, which in turn inherits properties from its parent class.
example:
class employee()://Super class
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
class childemployee1(employee)://First child class
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
class childemployee2(childemployee1)://Second child class
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
emp1 = employee('harshit',22,1000)
emp2 = childemployee1('arjun',23,2000)
print(emp1.age)
print(emp2.age)
Output: 22,23
interpretation:
- The code written above has already explained very clearly, here I define the superclass as employee, and the subclass as childemployee1. Now, childemployee1 acts as the parent of childemployee2.
- I have instantiated two objects "emp1" and "emp2", in which I passed the parameters "name" and "age" for emp1 from the superclasses "employee" and "name", "age, salary" and "id" , "Salary" "from the parent class "childemployee1"
Hierarchical inheritance:
Hierarchical inheritance enables multiple derived classes to inherit properties from the parent class.
example:
class employee():
def __init__(self, name, age, salary): //Hierarchical Inheritance
self.name = name
self.age = age
self.salary = salary
class childemployee1(employee):
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
class childemployee2(employee):
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
emp1 = employee('harshit',22,1000)
emp2 = employee('arjun',23,2000)
print(emp1.age)
print(emp2.age)
Output: 22,23
interpretation:
- In the above example, you can clearly see that there are two subclasses "childemployee1" and "childemployee2". They inherit functions from a common parent class "employees".
- The objects'emp1' and'emp2' are instantiated according to the parameters'name','age', and'salary'.
Multiple inheritance:
Multi-level inheritance allows a derived class to inherit properties from multiple base classes.
example:
class employee1()://Parent class
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
class employee2()://Parent class
def __init__(self,name,age,salary,id):
self.name = name
self.age = age
self.salary = salary
self.id = id
class childemployee(employee1,employee2):
def __init__(self, name, age, salary,id):
self.name = name
self.age = age
self.salary = salary
self.id = id
emp1 = employee1('harshit',22,1000)
emp2 = employee2('arjun',23,2000,1234)
print(emp1.age)
print(emp2.id)
Output: 22,1234
explanation: In the above example, I took two parent classes "employee1" and "employee2". There is also a subclass "childemployee", which inherits the parent class by instantiating the objects "emp1" and "emp2" for the parameters of the parent class.
This is all about inheritance. Moving on in object-oriented programming Python, let's delve into "polymorphism".
Polymorphism:
You must all have used GPS to navigate routes. According to traffic conditions, how many different routes you encounter at the same destination, isn't it magical? From a programming point of view, this is called "polymorphism". This is an OOP method in which a task can be performed in many different ways. In simple terms, it is a property of an object, which allows it to take many forms.
There are two types of polymorphism:
- Compile-time polymorphism
- Runtime polymorphism
Compile-time polymorphism:
Compile-time polymorphism is also called static polymorphism, which is resolved when the program is compiled. A common example is "method overloading". Let me show you a quick example of the same.
example:
class employee1():
def name(self):
print("Harshit is his name")
def salary(self):
print("3000 is his salary")
def age(self):
print("22 is his age")
class employee2():
def name(self):
print("Rahul is his name")
def salary(self):
print("4000 is his salary")
def age(self):
print("23 is his age")
def func(obj)://Method Overloading
obj.name()
obj.salary()
obj.age()
obj_emp1 = employee1()
obj_emp2 = employee2()
func(obj_emp1)
func(obj_emp2)
Output:
Harshit is his name
3000 is his salary
22 is his age
Rahul is his name
4000 is his salary
23 is his age
explanation:
- In the above program, I created two classes'employee1' and'employee2' and created functions for'name','salary' and'age', and printed the same value without getting it from the user.
- Now, welcome to the main part. I created a function with "obj" as a parameter and called all three functions, namely "name", "age" and "salary".
- Later, the objects emp_1 and emp_2 were instantiated for these two classes and the functions were simply called. This type is called method overloading, and it allows a class to have multiple methods with the same name.
Runtime polymorphism:
Runtime polymorphism is also called dynamic polymorphism, which is resolved at runtime. A common example of runtime polymorphism is "method coverage." Let me show you through an example for better understanding.
example:
class employee():
def __init__(self,name,age,id,salary):
self.name = name
self.age = age
self.salary = salary
self.id = id
def earn(self):
pass
class childemployee1(employee):
def earn(self)://Run-time polymorphism
print("no money")
class childemployee2(employee):
def earn(self):
print("has money")
c = childemployee1
c.earn(employee)
d = childemployee2
d.earn(employee)
Output: no money, rich
description: In the above example, I created two classes'childemployee1' and'childemployee2', which are derived from the same base class'employee'. This is a problem of not receiving the money but the other. The real question now is how did this happen? Well, if you look closely, I created an empty function here and used Pass (the statement used when you don't want to execute any commands or code). Now, under the two derived classes, I use the same empty function and use the print statement as'no money' and'has money'. Finally, two objects are created and the function is called.
Continue to discuss the next object-oriented Python programming method, I will discuss encapsulation.
Package:
In its original form, encapsulation basically means binding data into a single class. Unlike Java, Python does not have any private keywords. The class should not be accessed directly, but should be prefixed with an underscore.
Let me show you an example for better understanding.
example:
class employee(object):
def __init__(self):
self.name = 1234
self._age = 1234
self.__salary = 1234
object1 = employee()
print(object1.name)
print(object1._age)
print(object1.__salary)
Output:
1234
Backtracking (the last call):
1234
File "C:/Users/Harshit_Kant/PycharmProjects/test1/venv/encapsu.py", line 10, in
Printing (object1.__salary)
AttributeError:'employee' object has no attribute '__salary'
description: you will get this question, what is the underscore and error? Well, the python class treats private variables as inaccessible (__salary).
Therefore, I used setter methods in the next example, which provide indirect access to them.
example:
class employee():
def __init__(self):
self.__maxearn = 1000000
def earn(self):
print("earning is:{}".format(self.__maxearn))
def setmaxearn(self,earn)://setter method used for accesing private class
self.__maxearn = earn
emp1 = employee()
emp1.earn()
emp1.__maxearn = 10000
emp1.earn()
emp1.setmaxearn(10000)
emp1.earn()
Output:
The income is: 1000000, the income is: 1000000, the income is: 10000
Description: Use setter methods to provide indirect access to private class methods. Here I define an employee class, and use a (__maxearn), which is the setter method used to store the maximum income of the employee, and a setter function setmaxearn() with a price as a parameter.
This is an obvious example of encapsulation. We restrict access to private class methods and then use setter methods to grant access.
Next in object-oriented programming, python methodology discusses a key concept called abstraction.
abstract:
Suppose you book a movie ticket from bookmyshow using online banking or any other process. You don't know how to generate a pin or how to complete the verification process. This is called "abstraction" in terms of programming, and it basically means that you only show the implementation details of a specific process and hide the details from the user. It is used to simplify complex problems by modeling the classes suitable for the problem.
Abstract classes cannot be instantiated, which simply means that you cannot create objects for this type of class. It can only be used for inheritance functions.
example:
from abc import ABC,abstractmethod
class employee(ABC):
def emp_id(self,id,name,age,salary): //Abstraction
pass
class childemployee1(employee):
def emp_id(self,id):
print("emp_id is 12345")
emp1 = childemployee1()
emp1.emp_id(id)
Output: emp_id is 12345
Description of As you can see in the example above, we imported an abstract method, and the rest of the program has a parent class and a derived class. An object is instantiated for the "childemployee" base class, and abstract functions are being used.
Is Python 100% object-oriented?
Python does not have an access specifier like "private" in java. In addition to strong encapsulation, it supports most of the terms related to "object-oriented" programming languages. Therefore it is not completely object-oriented.
This brings us to the end of the article on "Object-Oriented Python Programming". I hope you have understood all the concepts related to classes, objects, and object-oriented concepts in Python. Make sure you practice as much as possible and regain your experience.
Click to follow, and get to know the fresh technology of Huawei Cloud for the first time~
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。