程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python interview high frequency question: what is self

編輯:Python

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 !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved