Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the four secrets of self in Python?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces to you what are the four secrets of self in Python, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The mystery of self

There is no doubt that almost every Python course has a lecture on (class) classes-one of the basic building blocks of object-oriented programming languages.

As you learn it through some examples, you'll notice that many functions defined in the Python class take self as their first argument. For example, in the following code snippet, we declare a class named Student whose first argument to the greet () method is self. However, the function doesn't use self at all, so where does the self here come from? This is the first riddle for many beginners.

Class Student:... Def greet (self, name):... Print ('Good Morning,' + name)... > > student = Student () > student.greet ('John') Good Morning, John

It's also strange that when we use this function, we don't set anything to the self parameter, which is another puzzle that bothers us. In this article, we will share some of the secrets of self in Python with learners.

1. What does it stand for?

Before we begin to deal with this puzzle, we need to understand two basic related concepts: classes and instances. Of course, solving all these puzzles requires additional knowledge, not just classes and examples, which I'll clarify in the next discussion. If you are familiar with both concepts, you can skip the next paragraph, which is just a brief overview of both concepts.

To create a Python class is to declare a new object type that provides a mechanism for bundling data and functionality. In the above example, we created a class named Student and used it to create an object of student type named Student. This object is called an instance of the student class. In addition, classes can provide specific functionality commonly referred to as attributes, such as the greet () function in the example. We use three introspection functions (type (), isinstance (), and hasattr ()) to check the relevant information.

> type (Student) > type (student) > isinstance (student, Student) True > hasattr (Student, 'greet') True

I can simply tell you that the self parameter in the greet () function is the student instance in the example above. More generally, it is the instance that calls this function. The following is supporting evidence:

Class Student:... Def greet (self, name):... Print (id (self))... Print ('Good Morning,' + name)... > > student = Student () > student.greet ('John') 4546580944 Good Morning, John > id (student) 4546580944

In the above code, we modified the greet () function and asked it to use the introspected id () function to show us the memory address of the self parameter. As you can see, the self parameter and the instance student are the same object because they have the same memory address.

two。 Why don't you set it in a function call?

Continuing the example shown in the previous section, when we use the instance student to call the greet () function, this function is often referred to as the instance method-- a function that is available to an instance of a class. However, if we check the type of this property, we will show something different.

> > student = Student () > student.greet

As mentioned above, the greet property of the instance student is called the binding method. Specifically, it is bound to the greet property of the Student class.

To understand exactly what this means, let's take a look at the following code:

> Student.greet (student, 'John') Good Morning, John

Combined with the example at the beginning, you may notice three things in this code:

The caller of this function is class Student, not instance student.

The self and name parameters are set in this call, which is different from ignoring the self parameter when student calls the initial function.

Both function calls produce the same output. They essentially use the same function.

By implementing this information, you may have guessed what happened behind the scenes when the greet () function was called using the instance student.

As shown in the figure above, when the instance student calls the greet ('John') method, the interpreter handles the function call and sends the caller (that is, instance student) and name parameters (that is, 'John') to the greet (self, name) function as a class Student, which prints "Good Morning, John".

For interested readers, here are a few things to know that will help you understand the mystery more deeply. When you create a Python class, the function it declares is the property of the class (called a function object). In other words, the class "owns" these functions. An instance of the class does not implement these functions directly. Instead, they will have the same properties (that is, instance methods) that are bound to the corresponding functions implemented in the class.

Is 3.self a key word?

It seems that in all these defined functions, we use self as their first argument. Some people may mistakenly think that self is the keyword reserved by Python for these use cases. However, this is not the case. Take a look at a simple example:

> def=5 File ", line 1 def=5 ^ SyntaxError: invalid syntax > > class=4 File", line 1 class=4 ^ SyntaxError: invalid syntax > self=3

As you probably know, def and class are keywords in Python, and we can't use them as variable names. However, we can use self as the variable name outside the context in which the function is defined, indicating that it is not a reserved keyword in Python.

4. Do we have to use self in these function declarations?

In the above example, we repeatedly refer to the greet () function. As we have already discussed, we implement this function as an instance method so that it can be used by all instances of the Student class. In this case, self is required. Here is some evidence:

Class Teacher:... Def say_hello (name):... Print ('Hello,' + name)... > > teacher = Teacher () > teacher.say_hello ('John') Traceback (most recent call last): File ", line 1, in TypeError: say_hello () takes 1 positional argument but 2 were given

Here's some analysis. As mentioned earlier, when the instance teacher calls the say_hello () method, what happens is to execute the teacher. Say _ hello () function and set the instance objects teacher and 'John' to function calls. This is why it is mistakenly said that "2" is given. This is contrary to the definition of a function, which has only one parameter (name).

However, there are two other things related to this mystery that you may want to know:

Although the declaration instance method needs to include the self parameter, it does not have to be named self. Using this name in this scenario is just a convention that every Python programmer can appreciate. Here is an example that can be named something else without causing any problems. Although it is grammatically correct, it is not recommended because it will only confuse other Python programmers:

Class Teacher:... Def say_hello (professor, name):... Print ('Hello,' + name)... > > teacher = Teacher () > teacher.say_hello ('John') Hello, John

You do not need to use the self parameter when declaring other functions, such as classes and static methods. A clear explanation of classes and static methods will be the subject of future articles. But what I can show here is that when we declare a class method, the function does have something similar to using self in the instance method, which is often called cls and refers to the class object itself. It has nothing to do with specific examples. Here is an example:

Class Student:... Def _ _ init__ (self, name):... Self.name = name... @ classmethod... Def with_names (cls, first_name, last_name):... Return cls (first_name +'+ last_name)... > > student = Student.with_names ('John',' Smith') > student.name 'John Smith' 's four secrets about self in Python are shared here. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report