Home > Backend Development > Python Tutorial > Understand the usage of self in Python

Understand the usage of self in Python

高洛峰
Release: 2017-03-03 15:17:26
Original
1628 people have browsed it

When I first started learning how to write classes in Python, I found it very troublesome. Why is it needed when defining but not when calling? Why can't it be simplified internally to reduce the number of keystrokes we have to do? You will understand all your doubts after reading this article.

self represents an instance of a class, not a class.

Example to illustrate:

class Test:
  def prt(self):
    print(self)
    print(self.__class__)
 
t = Test()
t.prt()
Copy after login

The execution results are as follows

<__main__.Test object at 0x000000000284E080>
<class &#39;__main__.Test&#39;>
Copy after login

It is obvious from the above example that self represents an instance of a class. And self.class points to the class.

self does not have to be written as self

There are many children who first learn other languages ​​​​and then learn Python, so they always feel that self is weird. If you want to write it as this, you can ?

Of course, just rewrite the above code.

class Test:
  def prt(this):
    print(this)
    print(this.__class__)
 
t = Test()
t.prt()
Copy after login

After changing to this, the running results are exactly the same.

Of course, it is best to respect the established habits and use self.

Can I not write self?

Inside the Python interpreter, when we call t.prt(), Python is actually interpreted as Test.prt(t ), that is to say, replace self with an instance of the class.

Interested children's shoes can rewrite the above t.prt() line, and the actual results after running will be exactly the same.

In fact, it has been partially explained that self cannot be omitted when defining. If you have to try it, please see below:

class Test:
  def prt():
    print(self)
 
t = Test()
t.prt()
Copy after login

The runtime reminder error is as follows: prt has no parameters when it is defined, but we forcibly pass a parameter when running.

As explained above, t.prt() is equivalent to Test.prt(t), so the program reminds us that we have passed one more parameter t.

Traceback (most recent call last):
 File "h.py", line 6, in <module>
  t.prt()
TypeError: prt() takes 0 positional arguments but 1 was given
Copy after login

Of course, it’s okay if we don’t pass a class instance in our definition and call. This is a class method.

class Test:
  def prt():
    print(__class__)
Test.prt()
Copy after login

The running results are as follows

<class &#39;__main__.Test&#39;>
Copy after login

When inheriting, which one is passed in Instance is the instance passed in, not the instance of the class in which self is defined.

Look at the code first

class Parent:
  def pprt(self):
    print(self)
 
class Child(Parent):
  def cprt(self):
    print(self)
c = Child()
c.cprt()
c.pprt()
p = Parent()
p.pprt()
Copy after login

The running results are as follows

<__main__.Child object at 0x0000000002A47080>
<__main__.Child object at 0x0000000002A47080>
<__main__.Parent object at 0x0000000002A47240>
Copy after login

Explanation:

There should be no understanding problem when running c.cprt(), which refers to an instance of the Child class.

But when running c.pprt(), it is equivalent to Child.pprt(c), so self still refers to an instance of the Child class. Since the pprt() method is not defined in self, inheritance is inherited Looking up the tree, we find that the pprt() method is defined in the parent class Parent, so it will be called successfully.

In the descriptor class, self refers to the instance of the descriptor class.

is not easy to understand. Let’s look at the example first:

class Desc:
  def __get__(self, ins, cls):
    print(&#39;self in Desc: %s &#39; % self )
    print(self, ins, cls)
class Test:
  x = Desc()
  def prt(self):
    print(&#39;self in Test: %s&#39; % self)
t = Test()
t.prt()
t.x
Copy after login

The running results are as follows:

self in Test: <__main__.Test object at 0x0000000002A570B8>
self in Desc: <__main__.Desc object at 0x000000000283E208>
<__main__.Desc object at 0x000000000283E208> <__main__.Test object at 0x0000000002A570B8> <class &#39;__main__.Test&#39;>
Copy after login

Most children's shoes have begun to have questions about why self is defined in the Desc class Shouldn't it be the instance t that calls it? How did it become an instance of the Desc class?

Note: You need to open your eyes to see clearly here. What is called here is t.x, which means it is the attribute x of the instance t of the Test class. Since the attribute x is not defined in the instance t, it is found. Class attribute x, and this attribute is a descriptor attribute, which is an instance of the Desc class, so there is no method that uses Test here.

Then if we call attribute x directly through the class, we can get the same result.

The following is the result of changing t.x to Test.x.

self in Test: <__main__.Test object at 0x00000000022570B8>
self in Desc: <__main__.Desc object at 0x000000000223E208>
<__main__.Desc object at 0x000000000223E208> None <class &#39;__main__.Test&#39;>
Copy after login

Digression: Since in many cases the descriptor class still needs to know who is the instance calling the descriptor, so there is a third The two parameters ins are used to represent the class instance that calls it, so when t. When calling using Test.x, None is returned because there is no instance.

Understand self in python from the essence of OO
For example, suppose I want to operate on the user's data. The user's data contains name and age. If process-oriented is used, the implementation will look like this.

def user_init(user,name,age): 
  user[&#39;name&#39;] = name 
  user[&#39;age&#39;] = age 
 
def set_user_name(user, x): 
  user[&#39;name&#39;] = x 
 
def set_user_age(user, x): 
  user[&#39;age&#39;] = x 
 
def get_user_name(user): 
  return user[&#39;name&#39;] 
 
def get_user_age(user): 
  return user[&#39;age&#39;] 
 
myself = {} 
user_init(myself,&#39;kzc&#39;,17) 
print get_user_age(myself) 
set_user_age(myself,20) 
print get_user_age(myself)
Copy after login

You can see that user parameters must be passed in for various operations on the user.
If you use object-oriented, you don't need to pass the user parameters back and forth every time. The relevant data and operations are bound in one place. Data can be easily obtained from various places in this class.
The reason why data can be accessed from various places in the class is that it is bound to self. Of course, the first parameter of its method does not need to be called self, but can be called another name. Self is just a convention.
The following is the object-oriented implementation. You can see that it is much more structured and clear and readable.

class User(object): 
  def __init__(self,name,age): 
    self.name = name 
    self.age = age 
 
  def SetName(self,name): 
    self.name = name 
 
  def SetAge(self,age): 
    self.age = age 
 
  def GetName(self): 
    return self.name 
 
  def GetAge(self): 
    return self.age 
 
u = User(&#39;kzc&#39;,17) 
print u.GetName() 
print u.GetAge()
Copy after login

As can be seen from the above example, object-oriented is actually quite useful, but most people don’t abstract it well, encapsulate it well, and make mistakes. application.

Summary

  • self needs to be defined when defining, but it will be automatically passed in when called.

  • The name of self is not fixed, but it is best to use self

    according to the agreement.
  • self always refers to the instance of the class when called.

For more articles related to understanding the usage of self in Python, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template