Python does not have an access specifier like “private” in Java. With the exception of strong encapsulation, it supports most of the terms associated with “object-oriented” programming languages. So it’s not completely object-oriented.

This article to share from huawei cloud community “from scratch to learn python | object-oriented programming python: everything you need to know”, the original author: Yuchuan.

Object-oriented programming as a discipline is widely followed among developers. Python, a popular programming language, also follows the object-oriented programming paradigm. It handles the declarations of Python classes and objects that underlie OOP concepts. This article on “Object-oriented Python programming” will walk you through four ways to declare Python classes, instantiate objects from them, and implement OOP.

What is object-oriented programming? (OOP concepts 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 rather than redundant code. Programs are divided into independent objects or several small programs. Each individual object represents a different part of the application and has its own logic and data to communicate within them.

Now, to get a clearer idea of why we use Oops instead of POP, I’ve listed the differences below.

The difference between object-oriented and procedural programming

That’s all there is to the difference, move on and let’s learn about Python OOPs Conceots.

What are Python OOP concepts?

The main OOP (object-oriented programming) concepts in Python include classes, objects, methods, inheritance, polymorphism, data abstraction, and encapsulation.

That’s all there is to the difference. Let’s move on to classes and objects.

What are classes and objects?

A class is a collection of objects, or you could say a blueprint for objects that define common properties and behaviors. Now the question is, how did you do it?

Well, it groups data logically in a way that makes it easy to reuse code. I can give you a real life example — think of an office thinking of “employee” as a class with all the attributes associated with it, such as “emp_name”, “emp_age”, “emp_salary”, “emp_id” as objects in Python. Let’s 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
Copy the code

Note: Python is case insensitive.

Object:

An object is an instance of a class. It is an entity with states and behaviors. In short, it is an instance of a class that can access data.

Syntax: obj= class1()

Here obJ is the “object” of class1.

Creating 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,200,2234) print(emp1.__dict__)//Prints dictionaryCopy the code

Note: ’emp1′ and ’emp2′ are objects instantiated against the class ‘Employee’. Here, the word (__dict__) is a “dictionary” that prints all the values of the object ’emp1′ based on the given arguments (name, age, salary). (__init__) is like a constructor that is called whenever an object is created.

I hope now that you don’t have any future problems dealing with “classes” and “objects.”

With that in mind, let me take you through object-oriented programming:

Object-oriented programming methods:

The object-oriented programming approach involves the following concepts.

  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction

Let’s take a closer look at the first concept of inheritance.

Inheritance:

Have heard a relative say something like “You look like your father/mother”, and the reason behind this is called ‘inheritance’. In programming terms, this generally means “inheriting or transferring features from a parent class to a subclass without modification.” The new classes are called derived/subclasses, and the classes derived from them are called parent **/ base ** classes.

Let’s look at each subtopic in detail.

Single inheritance:

Single-level inheritance enables derived classes to inherit characteristics from a single parent.

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)Copy the code

Output: 22

Explanation:

  • I’m using the parent class and creating a constructor (__init__), and the class itself is initializing properties with parameters (‘name’, ‘age’, and ‘salary’).
  • A subclass “childemployee” is created, which inherits the attributes of the parent class, and finally instantiates the objects “emp1” and “emp2” according to the arguments.
  • Finally, I have printed the age of EMP1. Well, you can do a lot of things, like printing whole dictionaries or names or salaries.

Multi-level inheritance:

Multi-level inheritance enables a derived class to inherit properties from its immediate parent, which in turn inherits properties from its parent.

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, 23200 0) print (emp1. Age) print (emp2. Age)Copy the code

Output: 22, 23

Explanation:

  • As the code above makes clear, 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”, Where I pass parameters “name”, “age”, “salary” and “ID” to emp1 from the superclass “Employee” and “name”, “age”, “salary” from the parent class “childemployee1”

Hierarchical inheritance:

Hierarchical inheritance enables multiple derived classes to inherit attributes from their 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('arjun', 30, 000) emp2 = employee('arjun', 30, 000)  print(emp1.age) print(emp2.age)Copy the code

Output: 22, 23

Explanation:

  • In the example above, you can clearly see that there are two subclasses “Childemployee1” and “Childemployee2”. They inherit functionality from a common parent, “employee.”
  • The objects ’emp1′ and ’emp2′ are instantiated with parameters ‘name’, ‘age’, ‘salary’.

Multiple inheritance:

Multi-level inheritance enables a derived class to inherit properties from more than one base class.

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, 23200 0123 4) print (emp1. Age) print (emp2. Id)Copy the code

Output: 22123 4

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 objects “emp1” and “emp2” with arguments to the parent class.

It’s all about inheritance, moving forward in object-oriented programming Python, let’s delve into “polymorphism”.

Polymorphism:

You’ve all used GPS navigation routes, and isn’t it amazing how many different routes you encounter at the same destination, depending on traffic conditions? From a programming perspective, this is called “polymorphism.” This is an OOP approach in which a task can be executed in many different ways. Simply put, it is a property of an object that allows it to take many forms.

There are two types of polymorphism:

  • Compile-time polymorphism
  • Runtime polymorphism

Compile-time polymorphism:

Compile-time polymorphism, also known as static polymorphism, is resolved when a 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)
Copy the code

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, where I create a function that takes “obj” and call all three functions, “name”, “age”, and “salary”.
  • Later, the objects EMP_1 and emp_2 are instantiated for these two classes and the function is simply called. This type, called method overloading, allows a class to have multiple methods with the same name.

Runtime polymorphism:

Runtime polymorphism, also known as dynamic polymorphism, is resolved at run time. A common example of runtime polymorphism is “method override.” Let me show you an example to better understand it.

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)
Copy the code

Output: No money, money

Note: In the above example, I created two classes ‘childemployee1’ and ‘childemployee2’, which derive from the same base class ‘Employee’. It is a matter of not receiving money and the other receiving it. Now the real question is how did this happen? Well, if you look carefully, I created an empty function here and used Pass (the statement you use 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 statements as ‘no money’ and ‘has money’. Finally, two objects are created and the function is called.

Moving on to the next object-oriented approach to Python programming, I’ll discuss encapsulation.

Packaging:

In its original form, encapsulation basically meant binding data into a single class. Unlike Java, Python does not have any private keywords. Classes should not be accessed directly, but should be prefixed with an underscore.

Let me show you an example to better understand.

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)
Copy the code

Output:

Backtracking (Last call) : 1234 file “C: / Users/Harshit_Kant/PycharmProjects/test1 / venv/encapsu py”, line 10, AttributeError in print (object1. __salary) : ‘Employee ‘object has no attribute’ __ salary ‘

** You will get this question, what are the underscores and errors? Well, Python classes treat private variables as if they are not directly accessible (__salary).

Therefore, I use 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()
Copy the code

Output:

Revenue: 1000000, revenue: 1000000, revenue: 10000

Note: 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 here to store the maximum employee income, and a setter function setMaxEarn () that takes a price.

This is an obvious example of encapsulation where we restrict access to private class methods and then use setter methods to grant access.

Next in object-oriented programming, the Python methodology discusses a key concept called abstraction.

Abstract:

Suppose you use online banking or any other process to book a movie ticket from BookmyShow. You don’t know how to generate a PIN or how to complete the verification process. This is called “abstraction” in programming terms, and it basically means that you only show the implementation details of a particular process and hide them from the user. It is used to simplify complex problems by modeling classes that fit the problem.

Abstract classes cannot be instantiated, which simply means that you cannot create objects for classes of this type. 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)
Copy the code

Output: emp_id is 12345

Note: As you can see in the example above, we import 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 functionality is being used.

Is Python 100% object-oriented?

Python does not have an access specifier like “private” in Java. With the exception of strong encapsulation, it supports most of the terms associated with “object-oriented” programming languages. So it’s not completely object-oriented.

This brings us to the end of our article on “Object-oriented Python programming.” I hope you have learned all the concepts related to classes, objects, and object-oriented concepts in Python. Make sure you practice and recover your experience as much as possible.

Click to follow, the first time to learn about Huawei cloud fresh technology ~