Python中的self的含義!

2021-09-10 08:06:37 字數 1498 閱讀 2115

>>> class test:

... def prt(self):

... print(self)

... print(self.__class__)

...>>> t = test()

>>> t.prt()

<__main__.test object at 0x000001ade41b1710>

# self代表的是類的例項。而self.__class__則指向類。

>>> t

<__main__.test object at 0x000001ade41b1710>

# 在python的直譯器內部,當我們呼叫t.prt()時,實際上python解釋成test.prt(t),也就是說把self替換成類的例項。

>>> test.prt(t)

<__main__.test object at 0x000001ade41b1710>

>>>

>>> class a(object):

... def go(self):

... self.one = "hello"

...>>> a1 = a()

>>> a1.go()

>>> a1.one

'hello'

# 使用類方法中的變數,需要例項化方法

>>> a2 = a()

>>> a2.one

traceback (most recent call last):

file "", line 1, in attributeerror: 'a' object has no attribute 'one'

# 用self修飾類方法中的變數,相當於是全域性變數

>>> class a:

... def prt(self):

... self.temp = "global_val"

...>>> a = a()

>>> a.prt()

>>> a.temp

'global_val'

# 不用self修飾類方法中的變數,相當於是區域性變數

>>> class b:

... def prt(self):

... temp = "local_val"

...>>> b = b()

>>> b.prt()

>>> b.temp

traceback (most recent call last):

file "", line 1, in attributeerror: 'b' object has no attribute 'temp'

>>>

Python中self的含義 進製轉換

1 一篇文章讓你徹底搞清楚python中self的含義 python中self用法詳解 python中self的含義 python self引數 函式詳解 2 python中0.3怎麼轉二進位制 python hex 函式 轉換為二進位制函式 bin 轉換為八進位制函式 oct 轉換為十進位制函式 ...

Python 理解類中self的含義

self代表的是類的例項,而不是類 class test object def prt self print self print self.class t test t.prt 執行結果 main test object at 0x10fe90fd0 從上面的執行結果可以看出,self指向是類的例...

object c 中的 self 含義

self就是當前例項的指標。所以 看這個例子 superclass subclass superclass import inte ce superclass nsobject void printself end implementation superclass void printself s...