What is self in Python class

Time:2020-3-19

When Python writes classes, the first parameter of each function parameter is self. At first, I didn’t care what it was, but I knew that it had to be written. Later, I became familiar with Python. Looking back at the concept of self, I seem to understand it.

First of all, it is clear that self only exists in the methods of a class. Independent functions or methods do not have to have self. Self is required when defining the methods of a class, although it is not necessary to pass in the corresponding parameters when calling.

Self name is not necessary. In Python, self is not a key word. You can define it as a or B or any other name. However, convention becomes vulgar (in order to unify with other programming languages and reduce the difficulty of understanding). Don’t try to be different. You won’t understand.

In the following example, change self to myname without any error:

class Person:
    def _init_(myname,name):
        myname.name=name
    def sayhello(myname):
        print 'My name is:',myname.name
p=Person('Bill')
print p

Self refers to the class instance object itself (Note: not the class itself).

class Person:
    def _init_(self,name):
        self.name=name
    def sayhello(self):
        print 'My name is:',self.name
p=Person('Bill')
print p

In the above example, self points to instance P of person. Why not point to the class itself, as shown in the following example:

class Person:
    def _init_(self,name):
        self.name=name
    def sayhello(self):
        print 'My name is:',self.name
p1=Person('Bill')
p2 = Person('Apple')
print p1

If self points to the class itself, which one does self point to when there are multiple instance objects?

summary

Self needs to be defined when it is defined, but is passed in automatically when it is called.

Self’s name is not prescribed to be dead, but it’s better to use self as agreed

Self always refers to an instance of the class at the time of the call.
From: https://www.cnblogs.com/chownjy/p/8663024.html