Home Backend Development Python Tutorial Understand self in Python in one article

Understand self in Python in one article

Aug 05, 2019 pm 06:01 PM
python self

Understand self in Python in one article

Magical self:

It is stipulated in the Python class that the first parameter of the function is the instance object itself , and by convention, write its name as self. Its function is equivalent to this in Java, which represents the object of the current class and can call properties and methods in the current class.

Class is an object-oriented design idea, and instance (that is, object, object) is created based on class.

A class (class) should contain data and methods for operating data. Generally speaking, it is attributes and functions (that is, calling methods).

Why use self in class class?

In the class code (function), you need to access the variables and functions in the current instance, that is, access the

corresponding variable (property) in Instance: Instance. PropertyNam, to read the previous value and write the new value.

Call the corresponding function (function): Instance.function(), that is, perform the corresponding action.

-> If you need to access the variables of the instance and call the functions of the instance, of course you need the corresponding instance Instance object itself.

-> It is stipulated in Python that the first parameter of the function must be the instance object itself, and it is recommended that, by convention, its name be written as self.

-> Therefore, we need self (need to use self).

First, the definition of a class in Python:

In python, a class is defined by the keyword class:

followed by The class name, namely Person, usually starts with a capital letter, followed by (object), indicating which class the class is inherited from. Usually, if there is no suitable inherited class, the object class is used. This is the final word for all classes. All classes will be inherited.

class Person(object):
    pass
Copy after login

Instantiate the Person class. The instantiation is created through class name ().

class Person(object):
    pass
student = Person()    # 创建类的实例化
print(student)
print(Person)
Copy after login

Understand self in Python in one article

As you can see, the variable student points to a Person object, and the following 0x0000026EE434D8D0 is the memory address. The address of each object is different, and the Person itself is is a class.

You can also bind attributes to instance variables, for example: bind the name and score attributes to student

class Person(object):
    pass
student = Person()
# print(student)
# print(Person)
student.name = "Gavin"     # 为实例变量 student 绑定 name 属性   类似于 赋值 操作
student.score = 100        # 为 其绑定  score 属性
print(student.name)
print(student.score)
Copy after login

Understand self in Python in one article

Although the above method can be an instance of the class Variable binding attributes are not convenient and elegant enough. Since classes can serve as templates, when creating an instance, we can forcefully fill in the attributes we think must be bound. In python, this is usually used in classes. One method, the def __init__(self) method, binds attributes such as name and score to the instance variable when it is created.

class Person(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
        
student = Person('Gavin',100)    #  传入 __init__ 方法中需要的参数
print(student.name)
print(student.score)
Copy after login

Understand self in Python in one article

If empty parameters are passed in, an error will be reported:

class Person(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
        
student = Person()      # 此处应该有参数传入,却没有传
print(student.name)
print(student.score)
Copy after login

Understand self in Python in one article

Note:

1. The first parameter of the __init__ method is always self, which represents the created instance itself. Therefore, inside the __init__ method, you can bind various attributes to self, because self points to the created instance itself.

2. When using the __init__ method, you cannot pass in empty parameters when creating an instance. You must pass in parameters that match the __init__ method, but self does not need to be passed. The python interpreter will do it by itself. Pass in instance variables.

Related recommendations: "Python Video Tutorial"

Defining multiple functions in a class to call each other

class Person(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y
        
    def add(self):
        sum = self.x + self.y
        return sum
    
    def square(self):
        squr = pow(self.x,2)+pow(self.y,2)
        return squr
    def add_square(self):
        c = self.add()+self.square()
        return c
        
student = Person(3,4)
print(student.add())
print(student.square())
print('--------- 我是可爱的分割线-----------')
print(student.add_square())
Copy after login

Understand self in Python in one article

As can be seen from the above examples, compared with ordinary functions, functions defined in classes have only two differences:

1. The first parameter is always self, and this parameter does not need to be passed when calling.

2. When functions in a class call each other, self must be added, as in the above example: c = self.add() self.square(), if self is not added, an error will be reported: The function is undefined, see the figure below:

Understand self in Python in one article

除此之外,类的方法和普通函数没甚区别,当然也可以使用 默认参数、可变参数和关键字参数,例子如下:

class Person(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y
        
        
    def add(self,z=16):         # 设置 默认变量 z =16,这只是个普通的局部变量,非实例变量,实例变量需要 
    self.z = z,这样定义
        sum = self.x + self.y + z
        return sum
    
    def square(self):
        squr = pow(self.x,2)+pow(self.y,2)
        return squr
    def add_square(self,z):        #  调用时传入变量,这也是个普通的局部变量,非实例变量 
        c = self.add()+self.square() + z
        return c
        
student = Person(3,4)
print(student.add())
print(student.square())
print('--------- 我是可爱的分割线-----------')
print(student.add_square(16))
Copy after login

Understand self in Python in one article

看了上述的例子可能还是不明白 self 到底是个什么鬼,为啥要使用 self 这鬼东西?没关系,往下看:

其实 self 这家伙简单的说就是把 class 中 定义的 变量和函数 变成 实例变量和实例函数,作为类 class 的成员,使得成员间能互相调用,而不需要从外部调用 数据(变量)和 方法(函数),以实现数据的封装,以上面的 Person 类为例:

创建实例的时候需要给出实例变量 x,y, 调用函数时给出 z ,调用很容易,却不知道内部实现的细节。

总之,类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都相互独立、互不影响;方法是与实例绑定的函数,和普通的函数不同,方法可以直接访问实例的数据。

其实 self 中存储的是实例变量和实例函数的属性,可以理解为一个字典( dict ),如:{'name':'zhang','age':'18'}就是这些。

注意只有数据属性,并没有创建新的类的方法。 类----->通过实例化生成----对象---->(对象只是一串类似于字典的数据,没有把类的里的方法复制给你,python没有new这个方法!)

class Person(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y
        
        
    def add(self,z=16):     # 设置 z 为实例变量,即 self.z = z, z 是 class 的一个成员了,而非普通局部变量
        self.z = z
        sum = self.x + self.y + z  # z虽然已被实例化,但是依然可以当作 普通变量来用
        return sum
    
    def square(self):
        squr = pow(self.x,2)+pow(self.y,2)
        return squr
    def add_square(self):        
        c = self.add()+self.square() + self.z  # 调用实例变量 z 
        return c
        
student = Person(3,4)
print(student.add())
print(student.square())
print('--------- 我是可爱的分割线-----------')
print(student.add_square())
print(student.z)          # 函数add 中的 z 被实例化以后,就可以利用实例化的方法访问它
Copy after login

Understand self in Python in one article

通过这个例子可以看出, z 本来是 add() 函数的默认形参,通过将其实例化,就可以在其他函数体内调用实例变量z

被实例化以后,就可以利用实例化的方法访问它。

那么 self 到底是什么?

class Box(object):
    def __init__(self, boxname, size, color):
        self.boxname = boxname
        self.size = size
        self.color = color  # self就是用于存储对象属性的集合,就算没有属性self也是必备的
 
    def open(self, myself):
        print('-->用自己的myself,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))
        print('-->用类自己的self,打开那个%s,%s的%s' % (self.color, self.size, self.boxname))
 
    def close(self):
        print('-->关闭%s,谢谢' % self.boxname)
 
 
b = Box('魔盒', '14m', '红色')
b.close()
b.open(b)  # 本来就会自动传一个self,现在传入b,就会让open多得到一个实例对象本身,print看看是什么。
print(b.__dict__)  # 这里返回的就是self本身,self存储属性,没有动作。
Copy after login

Understand self in Python in one article

self代表类的实例,而非类;self 就是 对象/实例 属性集合

Box 是个类-----》self 实例化------》 b对象/ 实例

class 抽象体------》实例化------》对象/实例,含有属性:{'boxname':'魔盒', ‘size’:‘14m’, 'color':'red'},即 self

self 看似是整个对象,实际上清楚地描述了类就是产生对象的过程,描述了 self 就是得到了 对象,所以 self 内的键值可以直接使用

正如自然界中一个有效的对象,必须包括:

1、描述对象的属性;2、对象的方法

所以 self是必须的,也是对象中重要的特性。

看下面的代码,感觉就更神奇了:

class Box(object):
    def myInit(mySelf, boxname, size, color):
        mySelf.boxname = boxname
        mySelf.size = size
        mySelf.color = color  # 自己写一个初始化函数,一样奏效,甚至不用self命名。其它函数当中用标准self
        return mySelf  # 返回给实例化过程一个对象!神奇!并且含有对象属性/字典
 
    # def __init__(self, boxname, size, color):
    #     self.boxname = boxname
    #     self.size = size
    #     self.color = color  #注释掉原来标准的初始化
 
    def open(self, myself):
        print(self)
        print('-->用自己的myself,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))
        print('-->用类自己的self,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))
 
    def close(self):
        print('-->关闭%s,谢谢' % self.boxname)
 
 
# 经过改造,运行结果和标准初始化没区别
 
b = Box().myInit('魔盒', '14m', '红色')
# b = Box('魔盒', '14m', '红色')#注释掉原来标准的初始化方法
b.close()
b.open(b)  # 本来就会自动传一个self,现在传入b,就会让open多得到一个实例对象本身,print看看是什么。
print(b.__dict__)  # 这里返回的就是self本身,self存储属性,没有动作。
Copy after login

Understand self in Python in one article

换个角度来讲,对类的操作有:

1、定义属性 ; 2、调用方法

对类的反馈有:

1、得到属性 ; 2、执行方法

在 class 类的函数中,为什么 self是必要的,因为 self 是对象的载体,可以理解成一个字典,看下面代码:

class Box(object):
    def myInit(mySelf, boxname, size, color):
        print(mySelf.__dict__)#显示为{}空字典
        mySelf.boxname = boxname
        mySelf.__dict__['aa'] = 'w'#甚至可以像字典一样操作
        mySelf.size = size
        mySelf.color = color  # 自己写一个初始化函数,一样奏效,甚至不用self命名。其它函数当中用标准self
        return mySelf  # 返回给实例化过程一个对象!神奇!并且含有对象属性/字典
 
    # def __init__(self, boxname, size, color):
    #     self.boxname = boxname
    #     self.size = size
    #     self.color = color  #注释掉原来标准的初始化
 
    def open(self, myself):
        print(self)
        print('-->用自己的myself,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))
        print('-->用类自己的self,打开那个%s,%s的%s' % (myself.color, myself.size, myself.boxname))
 
    def close(self):
        print('-->关闭%s,谢谢' % self.boxname)
 
 
# 经过改造,运行结果和标准初始化没区别
 
b = Box().myInit('魔盒', '14m', '红色')
# b = Box('魔盒', '14m', '红色')#注释掉原来标准的初始化方法
b.close()
b.open(b)  # 本来就会自动传一个self,现在传入b,就会让open多得到一个实例对象本身,print看看是什么。
print(b.__dict__)  # 这里返回的就是self本身,self存储属性,没有动作。
Copy after login

Understand self in Python in one article

注意此处的: mySelf.__dict__['aa'] = 'w'  #甚至可以像字典一样操作; 在 b.__dict__ 的结果中显示为:'aa':'w'

故可以把 self 理解成存储 实例化对象属性的字典(dict), self 存储属性,而没有动作执行。

self总是指调用时的类的实例。

python 中一些特殊的实例变量:

1、私有变量(private),只有内部可以访问,外部不能访问,私有变量是在名称前以两个下划线开头,如:__name,其实私有变量也不是完全不能被外部访问,不能直接访问是因为python解释器对外把 __name 变量改成了 _类名__name,所仍然可以通过 _类名__name 来访问 __name。

2、在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。

3. Instance variable names starting with an underscore, such as _name, are accessible externally. However, according to the convention, when you see such a variable, it means, "Although I It can be accessed, but please treat me as a private variable and do not access it at will."

The above is the detailed content of Understand self in Python in one article. For more information, please follow other related articles on the PHP Chinese website!

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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

How debian readdir integrates with other tools How debian readdir integrates with other tools Apr 13, 2025 am 09:42 AM

The readdir function in the Debian system is a system call used to read directory contents and is often used in C programming. This article will explain how to integrate readdir with other tools to enhance its functionality. Method 1: Combining C language program and pipeline First, write a C program to call the readdir function and output the result: #include#include#include#includeintmain(intargc,char*argv[]){DIR*dir;structdirent*entry;if(argc!=2){

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Nginx SSL Certificate Update Debian Tutorial Nginx SSL Certificate Update Debian Tutorial Apr 13, 2025 am 07:21 AM

This article will guide you on how to update your NginxSSL certificate on your Debian system. Step 1: Install Certbot First, make sure your system has certbot and python3-certbot-nginx packages installed. If not installed, please execute the following command: sudoapt-getupdatesudoapt-getinstallcertbotpython3-certbot-nginx Step 2: Obtain and configure the certificate Use the certbot command to obtain the Let'sEncrypt certificate and configure Nginx: sudocertbot--nginx Follow the prompts to select

GitLab's plug-in development guide on Debian GitLab's plug-in development guide on Debian Apr 13, 2025 am 08:24 AM

Developing a GitLab plugin on Debian requires some specific steps and knowledge. Here is a basic guide to help you get started with this process. Installing GitLab First, you need to install GitLab on your Debian system. You can refer to the official installation manual of GitLab. Get API access token Before performing API integration, you need to get GitLab's API access token first. Open the GitLab dashboard, find the "AccessTokens" option in the user settings, and generate a new access token. Will be generated

How to configure HTTPS server in Debian OpenSSL How to configure HTTPS server in Debian OpenSSL Apr 13, 2025 am 11:03 AM

Configuring an HTTPS server on a Debian system involves several steps, including installing the necessary software, generating an SSL certificate, and configuring a web server (such as Apache or Nginx) to use an SSL certificate. Here is a basic guide, assuming you are using an ApacheWeb server. 1. Install the necessary software First, make sure your system is up to date and install Apache and OpenSSL: sudoaptupdatesudoaptupgradesudoaptinsta

What service is apache What service is apache Apr 13, 2025 pm 12:06 PM

Apache is the hero behind the Internet. It is not only a web server, but also a powerful platform that supports huge traffic and provides dynamic content. It provides extremely high flexibility through a modular design, allowing for the expansion of various functions as needed. However, modularity also presents configuration and performance challenges that require careful management. Apache is suitable for server scenarios that require highly customizable and meet complex needs.

See all articles