Python During the interview , If you want to assess the interviewer's understanding of the object , I will ask such a question , Please talk about it yes self The understanding of the ?
self This is very common , Let's define a python Class , The first parameter is self, The code is as follows :
class MyDemo:
def test_self(self):
pass
So we really understand what is self Do you ? I believe there are many students , Simply remember : This is a python A fixed way to define class methods in , Yes self Is the class method , No, self That's the function ! You bet , This is a python The difference between the most basic methods and functions in . that self And what is the essence of it , In fact, it is the instantiation object of the class ! That is, who is using a certain method ,self That's it .
Let's look at the following example
class MyClass:
def test_self(self):
print(self)
print("---------- First instance ----------")
my=MyClass()
print(my)
my.test_self()
print("---------- Second example ----------")
my1=MyClass()
print(my)
print(my1)
Output :
<__main__.MyClass object at 0x00000066AF550448>
<__main__.MyClass object at 0x00000066AF550448>
---------- Second example ----------
<__main__.MyClass object at 0x00000066AF550448>
<__main__.MyClass object at 0x00000066AF550388>
From the output of the second instance, we can see , We have instantiated two instances , One is <__main__.MyClass object at 0x00000066AF550448>, The other is <__main__.MyClass object at 0x00000066AF550388>
Continuing with the analysis, we can see that in the first example , Instantiated my And methods test_self(self) Medium self The value of is actually the same !
So we can come to a conclusion :self Is the instantiated object !