This article covers the content of Python classes and objects

This article covers the content of Python classes and objects

[Issue] is recommended if you can not just grab a key commodity spike hand speed, and it is in the studio: a large-scale ultra-low latency live, click to see hard-core solutions Huawei cloud audio and video.

Summary: This is all about Python classes and objects.

This article is shared from HUAWEI CLOUD Community "Learning Python| Python Classes and Objects Object-Oriented Programming" , the original author: Yuchuan

After Python will surpass other languages in terms of active developers, the demand for Python developers will only grow. Python follows an object-oriented programming paradigm. It handles declaring python classes, creating objects from them and interacting with users. In object-oriented languages, programs are divided into independent objects, or you can say that they are several small programs. Each object represents a different part of the application, and they can communicate with each other.

In this python class blog, you will learn about the various aspects of classes and objects in the following order:

What is a Python Class?

Methods and Attributes in a class

What are Objects?

OOPs Concepts:

  • Inheritance

  • Polymorphism

  • Abstraction

What are Python classes?

Classes in python are blueprints for creating specific objects. It allows you to build software in a specific way. The question is coming, what should I do? Classes allow us to logically group our data and functions in a way that is easy to reuse, and build them when needed. Consider the picture below.

In the first picture (A), it represents the blueprint of a house that can be regarded as a Class . Using the same blueprint, we can create multiple houses, which can be regarded as Objects . Using classes, you can add consistency to your programs so that you can use them in a more concise and effective way. Attributes are data members (class variables and instance variables) and methods accessed through dot notation.

  • Class variables are variables shared by all different objects/instances of a class .

  • Instance variables are unique variables for each instance. It is defined inside the method and only belongs to the current instance of the class.

  • Methods are also called functions. They are defined in the class and describe the behavior of the object.

Now, let's move on and see how it works in PyCharm. To get started, first look at the syntax of the python class.

Syntax :

class Class_name: statement-1 . . statement-N Copy code

Here, the "class" statement creates a new class definition. The name of the class immediately follows the keyword "class" in python, followed by a colon. To create a class in python, consider the following example:

class employee: pass #no attributes and methods emp_1=employee() emp_2=employee() #instance variable can be created manually emp_1.first='aayushi' emp_1.last='Johari' emp_1.email='aayushi@edureka.co' emp_1.pay=10000 emp_2.first='test' emp_2.last='abc' emp_2.email='test@company.com' emp_2.pay=10000 print(emp_1.email) print(emp_2.email) Copy code

Output

aayushi@edureka.co test@company.com Copy code

Now, what if we don't want to set these variables manually. You will see a lot of code, and it is easy to make mistakes. So in order to make it automatic, we can use the "init" method. For this, let us understand what the methods and attributes in Python classes are.

Methods and attributes in Python classes

Without some features, creating a class now is incomplete. Therefore, functions can be defined by setting various attributes, which act as containers for data and functions related to these attributes. Functions in python are also called methods . Speaking of the init method, it is a special function that will be called whenever a new object of the class is instantiated. You can think of it as the initialize method, or if you come from any other object-oriented programming background, such as C++, Java, etc., you can think of it as a constructor. Now when we set up methods in the class, they will automatically receive the instance. Let's continue to use the python class and use this method to accept the first name, last name, and salary.

class employee: def __init__(self, first, last, sal): self.fname=first self.lname=last self.sal=sal self.email=first +'.' + last +'@company.com' emp_1=employee('aayushi','johari',350000) emp_2=employee('test','test',100000) print(emp_1.email) print(emp_2.email) Copy code

Now in our "init" method, we set these instance variables (self, first, last, sal). Self is an instance, which means that whenever we write self.fname=first, it is the same as emp_1.first='aayushi'. Then we created an instance of the employee class, in which we can pass the value specified in the init method. This method takes the instance as a parameter. Now it will be done automatically instead of manually.

Next, we want to be able to perform some kind of operation. To this end, we will add such a method . Suppose I want to display the function of the employee's full name. So let us actually achieve this.

class employee: def __init__(self, first, last, sal): self.fname=first self.lname=last self.sal=sal self.email=first +'.' + last +'@company.com' def fullname(self): return'{}{}'.format(self.fname,self.lname) emp_1=employee('aayushi','johari',350000) emp_2=employee('test','test',100000) print(emp_1.email) print(emp_2.email) print(emp_1.fullname()) print(emp_2.fullname()) Copy code

Output

aayushi.johari@company.com test.test@company.com aayushijohari TESTTEST Copy code

As you can see above, I created a method called "full name" in a class. Therefore, every method in the python class will automatically take the instance as the first parameter. Now in this method, I wrote the logic to print the full name and return this instead of the emp_1 first name and last name. Next, I used "self" so that it applies to all instances. So every time we print this, we use a method .

Continuing to use Python classes, there are some variables that are shared between all instances of the class. These are called class variables . Instance variables can be unique for each instance, such as name, email, sal, etc. Is it complicated? Let us understand this through an example. Please refer to the code below to understand the annual salary increase.

class employee: perc_raise =1.05 def __init__(self, first, last, sal): self.fname=first self.lname=last self.sal=sal self.email=first +'.' + last +'@company.com' def fullname(self): return'{}{}'.format(self.fname,self.lname) def apply_raise(self): self.sal=int(self.sal*1.05) emp_1=employee('aayushi','johari',350000) emp_2=employee('test','test',100000) print(emp_1.sal) emp_1.apply_raise() print(emp_1.sal) Copy code

Output

350000 367500 Copy code

As you can see above, I printed the salary first, and then applied a 1.5% increase. In order to access these class variables, we need to access them through the class or an instance of the class. Now, let us understand the various attributes in the Python class.

Attributes in Python classes

Attributes in Python define the attributes of an object, element, or file. There are two types of attributes:

  • Built-in class attributes: There are various built-in attributes in Python classes. For example, _dict_, _doc_, _name _, etc. Let me give the same example, I want to view all the key-value pairs of employee1. To do this, you can simply write the following statement containing the class namespace:

    Print (emp_1. dict )

After execution, you will get this output: {'fname':'aayushi','lname':'johari','sal': 350000,'email':' aayushi.johari@company.com '}

  • User-defined attributes : The attributes are created in the class definition. We can dynamically create new properties for existing instances of the class. Properties can also be bound to class names.

Next, we have public, protected and private attributes. Let us understand them in detail:

Next, let us understand the most important component of a python class, namely Objects.

As we discussed above, an object can be used to access different properties. It is used to create an instance of the class. An instance is an object of a class created at runtime.

To give you a quick glance, the object is mainly to see everything around. For example: Dog is an object of animal type, I am an object of human type. Similarly, the same phone class can have different objects. This is very similar to the function call we have already discussed. Let us understand this through an example:

class MyClass: def func(self): print('Hello') # create a new MyClass ob = MyClass() ob.func() Copy code

Continue to use python classes, let us understand various OOP concepts.

Object-oriented concept

OOPs refers to object-oriented programming in Python. Well, Python is not fully object-oriented, because it contains some procedural functions. Now, you must be wondering what is the difference between procedural programming and object-oriented programming. In order to eliminate your doubts, in procedural programming, the entire code is written into a long procedure, even if it may contain functions and subroutines. Because data and logic are mixed together, they cannot be managed. But when we talk about object-oriented programming, the program is split into independent objects or several small programs. Each object represents a different part of the application, and these parts have their own data and logic to communicate between them. For example, a website has different objects, such as images, videos, etc.

Object-oriented programming includes concepts such as Python classes, objects, inheritance, polymorphism, and abstraction. Let us understand these topics in detail below.

Python classes: inheritance

Inheritance allows us to inherit properties and methods from the base class/parent class. This is useful because we can create subclasses and get all the functionality from the parent class. Then we can override and add new features without affecting the parent class. Let us use an example to understand the concept of parent class and subclass.

As we can see in the image, the child inherits the attributes of the father. Similarly, in python, there are two classes:

1. The parent class (Super or Base class)

2. Subclass (subclass or derived class)

A class that inherits attributes is called a child class, and a class that inherits attributes is called a parent class.

Inheritance refers to the ability to create specialized subclasses that contain its parent class . It is further divided into four types, namely single inheritance, multi-level inheritance, hierarchical inheritance and multiple inheritance. Please refer to the figure below for a better understanding.

Let's continue to use python classes and understand how inheritance is useful.

For example, I want to create classes for employee types. I will create'developers' and'managers' as subcategories, because developers and managers have names, emails, and salaries, and all of these functions are in the employee category. Therefore, we don't have to copy the code of the subclass, but can simply reuse the code by inheriting from the employee.

class employee: num_employee=0 raise_amount=1.04 def __init__(self, first, last, sal): self.first=first self.last=last self.sal=sal self.email=first +'.' + last +'@company.com' employee.num_employee+=1 def fullname (self): return'{} {}'.format(self.first, self.last) def apply_raise (self): self.sal=int(self.sal * raise_amount) class developer(employee): pass emp_1=developer('aayushi','johari', 1000000) print(emp_1.email) Output-aayushi.johari@company.com Copy code

As you can see in the above output, all the details of the employee class can be found in the developer class. Now, what if I want to change the raise_amount of the developer to 10%? Let's see how it is actually done.

class employee: num_employee=0 raise_amount=1.04 def __init__(self, first, last, sal): self.first=first self.last=last self.sal=sal self.email=first +'.' + last +'@company.com' employee.num_employee+=1 def fullname (self): return'{} {}'.format(self.first, self.last) def apply_raise (self): self.sal=int(self.sal* raise_amount) class developer(employee): raise_amount = 1.10 emp_1=developer('aayushi','johari', 1000000) print(emp_1.raise_amount) Output-1.1 Copy code

As you can see, it has updated the salary increase percentage from 4% to 10%. Now, if I want to add another attribute, such as using a programming language in our init method, but it does not exist in our parent class. Is there any solution? Yes it is! We can copy the entire employee logic and do this, but it will increase the code size again. So, to avoid this situation, let us consider the following code:

class employee: num_employee=0 raise_amount=1.04 def __init__(self, first, last, sal): self.first=first self.last=last self.sal=sal self.email=first +'.' + last +'@company.com' employee.num_employee+=1 def fullname (self): return'{} {}'.format(self.first, self.last) def apply_raise (self): self.sal=int(self.sal* raise_amount) class developer(employee): raise_amount = 1.10 def __init__(self, first, last, sal, prog_lang): super().__init__(first, last, sal) self.prog_lang=prog_lang emp_1=developer('aayushi','johari', 1000000,'python') print(emp_1.prog_lang) Copy code

So, with just a little bit of code, I made the change. I used super.__init__(first, last, pay) which inherited the attributes of the base class. In short, inheritance is used to reuse code and reduce the complexity of the program.

Python classes: polymorphism

Polymorphism in computer science is the ability to present the same interface to different underlying forms. In fact, polymorphism means that if class B inherits from class A, it does not have to inherit everything about class A, it can do something different from class A. It is most commonly used to deal with inheritance. Python is implicitly polymorphic, and it can overload standard operators so that they behave appropriately according to the context.

Let us understand through an example:

class Animal: def __init__(self,name): self.name=name def talk(self): pass class Dog(Animal): def talk(self): print('Woof') class Cat(Animal): def talk(self): print('MEOW!') c = Cat('kitty') c.talk() d=Dog(Animal) d.talk() Copy code

Output

Meow! Woof Copy code

Next, let us turn to another object-oriented programming concept, namely abstraction.

Python class: abstract

Abstraction is used to simplify complex realities by modeling classes that fit the problem. Here, we have an abstract class that cannot be instantiated. This means that you cannot create objects or instances of these classes. It can only be used to inherit certain functions that you call base classes. Therefore, you can inherit functionality, but at the same time, you cannot create an instance of this particular class. Let us understand the concept of abstract classes through the following examples:

from abc import ABC, abstractmethod class Employee(ABC): @abstractmethod def calculate_salary(self, sal): pass class Developer(Employee): def calculate_salary(self, sal): finalsalary= sal*1.10 return finalsalary emp_1 = Developer() print(emp_1.calculate_salary(10000)) Copy code

Output

11000.0Copy code

As you can see in the output above, we have increased the basic salary to 10%, which means that the current salary is 11,000. Now, if you really continue to create an object of the "Employee" class, it will throw an error, because python will not allow you to create an object of the abstract class. But with inheritance, you can actually inherit properties and perform corresponding tasks.

Click to follow to learn about Huawei Cloud's fresh technology for the first time