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

Understand self in Python in one article

爱喝马黛茶的安东尼
Release: 2019-08-05 18:01:21
forward
4235 people have browsed it

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!

Related labels:
source:csdn.net
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