search
HomeBackend DevelopmentPython TutorialUnderstand the usage of self in Python

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()

The execution results are as follows

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

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()

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()

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

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()

The running results are as follows

<class &#39;__main__.Test&#39;>

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()

The running results are as follows

<__main__.Child object at 0x0000000002A47080>
<__main__.Child object at 0x0000000002A47080>
<__main__.Parent object at 0x0000000002A47240>

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

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;>

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;>

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)

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()

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!


Statement
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
How to Use Python to Find the Zipf Distribution of a Text FileHow to Use Python to Find the Zipf Distribution of a Text FileMar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How to Download Files in PythonHow to Download Files in PythonMar 01, 2025 am 10:03 AM

Python provides a variety of ways to download files from the Internet, which can be downloaded over HTTP using the urllib package or the requests library. This tutorial will explain how to use these libraries to download files from URLs from Python. requests library requests is one of the most popular libraries in Python. It allows sending HTTP/1.1 requests without manually adding query strings to URLs or form encoding of POST data. The requests library can perform many functions, including: Add form data Add multi-part file Access Python response data Make a request head

How Do I Use Beautiful Soup to Parse HTML?How Do I Use Beautiful Soup to Parse HTML?Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in PythonImage Filtering in PythonMar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using PythonHow to Work With PDF Documents Using PythonMar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django ApplicationsHow to Cache Using Redis in Django ApplicationsMar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

Introducing the Natural Language Toolkit (NLTK)Introducing the Natural Language Toolkit (NLTK)Mar 01, 2025 am 10:05 AM

Natural language processing (NLP) is the automatic or semi-automatic processing of human language. NLP is closely related to linguistics and has links to research in cognitive science, psychology, physiology, and mathematics. In the computer science

How to Perform Deep Learning with TensorFlow or PyTorch?How to Perform Deep Learning with TensorFlow or PyTorch?Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software