Python下一切皆對象,每個對象都有多個屬性(attribute),Python對屬性有一套統一的管理方案。
__dict__與dir()的區別:
dir()是一個函數,返回的是list;
__dict__是一個字典,鍵為屬性名,值為屬性值;
dir()用來尋找一個對象的所有屬性,包括__dict__中的屬性,__dict__是dir()的子集;
并不是所有對象都擁有__dict__屬性。許多內建類型就沒有__dict__屬性,如list,此時就需要用dir()來列出對象的所有屬性。
__dict__屬性
__dict__是用來存儲對象屬性的一個字典,其鍵為屬性名,值為屬性的值。
#!/usr/bin/python
# -*- coding: utf-8 -*-
class A(object):
class_var = 1
def __init__(self):
self.name = 'xy'
self.age = 2
@property
def num(self):
return self.age + 10
def fun(self):pass
def static_f():pass
def class_f(cls):pass
if __name__ == '__main__':#主程序
a = A()
print a.__dict__ #{'age': 2, 'name': 'xy'} 實例中的__dict__屬性
print A.__dict__
'''
類A的__dict__屬性
{
'__dict__':
, #這里如果想深究的話查看參考鏈接5
'__module__': '__main__', #所處模塊
'num':
, #特性對象
'class_f':
, #類方法
'static_f':
, #靜態方法
'class_var': 1, 'fun':
, #類變量
'__weakref__':
,
'__doc__': None, #class說明字符串
'__init__':
}
'''
a.level1 = 3
a.fun = lambda :x
print a.__dict__ #{'level1': 3, 'age': 2, 'name': 'xy','fun':
at 0x>}
print A.__dict__ #與上述結果相同
A.level2 = 4
print a.__dict__ #{'level1': 3, 'age': 2, 'name': 'xy'}
print A.__dict__ #增加了level2屬性
print object.__dict__
'''
{'__setattr__':
,
'__reduce_ex__':
,
'__new__':
,
等.....
'''
從上述代碼可知,
實例的__dict__僅存儲與該實例相關的實例屬性,
正是因為實例的__dict__屬性,每個實例的實例屬性才會互不影響。
類的__dict__存儲所有實例共享的變量和函數(類屬性,方法等),類的__dict__并不包含其父類的屬性。
dir()函數
dir()是Python提供的一個API函數,dir()函數會自動尋找一個對象的所有屬性(包括從父類中繼承的屬性)。
一個實例的__dict__屬性僅僅是那個實例的實例屬性的集合,并不包含該實例的所有有效屬性。所以如果想獲取一個對象所有有效屬性,應使用dir()。
print dir(A)
'''
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'class_f', 'class_var', 'fun', 'level1', 'level2', 'name', 'num', 'static_f']
'''
a_dict = a.__dict__.keys()
A_dict = A.__dict__.keys()
object_dict = object.__dict__.keys()
print a_dict
print A_dict
print object_dict
'''
['fun', 'level1', 'age', 'name']
['__module__', 'level2', 'num', 'static_f', '__dict__', '__weakref__', '__init__', 'class_f', 'class_var', 'fun', '__doc__']
['__setattr__', '__reduce_ex__', '__new__', '__reduce__', '__str__', '__format__', '__getattribute__', '__class__', '__delattr__', '__subclasshook__', '__repr__', '__hash__', '__sizeof__', '__doc__', '__init__']
'''
#因為每個類都有一個__doc__屬性,所以需要去重,去重后然后比較
print set(dir(a)) == set(a_dict + A_dict + object_dict) #True
dir()函數會自動尋找一個對象的所有屬性,包括__dict__中的屬性。
__dict__是dir()的子集,dir()包含__dict__中的屬性
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

