關(guān)于dict和dir()的區(qū)別和作用請參考這篇文章:http://blog.csdn.net/lis_12/article/details/53521554
說下我當(dāng)時遇到的問題:
class Demo:
def __init__(self, name, age):
self.name = name
self.age = age
def func(self):
print('Hello {0}'.format(self.name))
>>> d1 = Demo('Pythoner', 24)
>>> hasattr(d1, 'func')
True
>>> d1.__dict__
{'age': 24, 'name': 'Pythoner'}
>>dir(d1)
[ 'age', 'func', 'name','__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
首先,我們知道實(shí)例方法也可以算作是屬性,通過hasattr()函數(shù)可以驗(yàn)證.而 __dict__是用來存儲對象屬性的一個字典,但是它的返回值中并沒有'func'!
再看dir()函數(shù),它會自動尋找一個對象的所有屬性(包括從父類中繼承的屬性),它的返回值中有'func'.
所以我推測,"實(shí)例方法"并不屬于實(shí)例的"私有"屬性,而是該類的所有實(shí)例所共享的屬性!
實(shí)例得到私有屬性需要一個"私有化"的過程,就像__init__初始化函數(shù)!
驗(yàn)證:
class Demo2:
def __init__(self, name):
self.name = name
def func(self):
print('----get arg country----')
self.country = 'China'
>>> d2 = Demo2('Pythoner')
>>> d2.__dict__
{'name': 'Pythoner'}
>>> d2.func()
----get arg country----
>>> d2.__dict__
{'country': 'China', 'name': 'Pythoner'}
"實(shí)例方法"之所以被稱為實(shí)例方法,或者說每個實(shí)例執(zhí)行實(shí)例方法會因?yàn)楦髯运接袑傩缘牟煌a(chǎn)生不同的結(jié)果,是因?yàn)榉椒ㄖ械?code>self參數(shù).
實(shí)例在執(zhí)行實(shí)例方法時會在其所屬的類中尋找該方法,然后通過self
參數(shù)將實(shí)例本身傳遞進(jìn)去,實(shí)例的私有屬性就一并進(jìn)行了傳遞.通過self
參數(shù)就實(shí)現(xiàn)了實(shí)例和方法的綁定.
以上內(nèi)容均為個人理解,如有誤區(qū)請指點(diǎn),萬分感謝!