Comprehensive understanding of self in Python

For students who are new to Python, self is often seen in classes. So, what is self?

This has to start with object orientation. Python has been an object-oriented language from the beginning. It is easy to create classes and objects in Python.

For example, the following code snippet: defines aclassEmployee

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class Employee:
   'Base class for all employees'
   empCount = 0
 
   def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount + = 1
   
   def displayCount(self):
     print("Total Employee %d" % Employee.empCount)
 
   def displayEmployee(self):
      print("Name : ", self.name, ", Salary: ", self.salary)

Classes actually define things in the real world, people, objects, etc., any noun class. For example, employees defined above.

The definition is just a definition. We have defined that employees have attributes such as name and salary. However, for a specific employee, the values of these attributes are generally different. How would you describe a specific employee?

With the definition in place, we can create instances so that we can describe a specific employee. In other programming languages, the keyword new is generally used to create instances of a class, but there is no such keyword in Python. The instantiation of a class is similar to a function call.

Code below: Instantiates the Employee class

"Create the first object of the Employee class"
emp1 = Employee("张三", 2000)
"Create a second object of class Employee"
emp2 = Employee("王五", 5000)

Note: The init() method is a special method, called the constructor or initialization method of a class. This method will be called when an instance of this class is created.

And what is self? self is actually a placeholder that represents an instance of a class. When we use the above code to create an emp1 instance, it represents the emp1 instance; when we create emp2, it represents the emp2 instance.

Therefore, when we call the following instance methods, the values of the corresponding attributes of the instance will be output:

emp1.displayEmployee()
emp2.displayEmployee()

Name: Zhang San, Salary: 2000
Name: Wang Wu, Salary: 5000

self is associated with an instance of a class. Of course, some properties and methods of the class itself exist without instantiation, so don’t get confused.

For example, the custom class attribute empCount in the previous code. As well as, the built-in properties described below.

Built-in properties of Python classes

  • dict: a collection of class attributes: including custom attributes
  • doc: Class documentation string
  • name: class name
  • module: The module where the class definition is located
  • bases : All parent class elements of the class

implement:

print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)

Output:

Employee.__doc__: base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: (<class 'object'>,)
Employee.__dict__: {'__module__': '__main__', '__doc__': 'Base class for all employees', 'empCount': 2, '__init__': <function Employee .__init__ at 0x0000025F73518550>, 'displayCount': <function Employee.displayCount at 0x0000025F735185E0>, 'displayEmployee': <function Employee.displayEmployee at 0x0000025F73518670>, '__dict__': <attribute '__dict__' of 'Employee' objects>, '__weakref__': <attribute '__weakref__' of 'Employee' objects>}

There are also some built-in methods in Python that will be executed automatically under certain circumstances.

  • init

As mentioned earlier, when instantiated, it will be called and executed.

  • new

Automatically triggered before __init__ is triggered. When calling this class, the method is the real class construction method, which is used to generate instantiated objects (empty attributes). Therefore, you can override the __new__ method to control the object generation process

  • del

Used to be automatically called when the reference count of the object is 0. Generally called during garbage collection.

Does self have to be used in class?

Not necessarily, for example when we define a “static class”:

class util:
   def checkEmployee(emp):
      if isinstance(emp, Employee):
          print("Name : ", emp.name, ", Salary: ", emp.salary)
      else:
          print("%s is not an Employee" % emp)

Suppose we design a tool class util: used to detect whether the incoming parameter is of type Employee. If so, it will be processed further.

Look at the code snippet below:

emp3 = "李思"

util.checkEmployee(emp1)
util.checkEmployee(emp2)
util.checkEmployee(emp3)

Output:

Name: Zhang San, Salary: 2000
Name: Wang Wu, Salary: 5000
John Doe is not an Employee


———————————END——————- ——–

Digression

Thank you for watching until the end, I have prepared some benefits for everyone!

Interested friends will receive a complete set of Python learning materials, including interview questions, resume information, etc. See below for details.


CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

1. Python learning routes in all directions

The technical points in all directions of Python have been compiled to form a summary of knowledge points in various fields. Its usefulness is that you can find corresponding learning resources according to the following knowledge points to ensure that you learn more comprehensively.

img
img

2. Python essential development tools

The tools have been organized for you, and you can get started directly after installation! img

3. Latest Python study notes

When I learn a certain basic and have my own understanding ability, I will read some books or handwritten notes compiled by my seniors. These notes record their understanding of some technical points in detail. These understandings are relatively unique and can be learned. to a different way of thinking.

img

4. Python video collection

Watch a comprehensive zero-based learning video. Watching videos is the fastest and most effective way to learn. It is easy to get started by following the teacher’s ideas in the video, from basic to in-depth.

img

5. Practical cases

What you learn on paper is ultimately shallow. You must learn to type along with the video and practice it in order to apply what you have learned into practice. At this time, you can learn from some practical cases.

img

6. Interview Guide

Resume template

CSDN gift package:The most complete “Python learning materials” on the Internet are given away for free! (Safe link, click with confidence)

If there is any infringement, please contact us for deletion.