2012-05-10 62 views
5

我正在學習Python,並且我試圖更好地理解描述符。當我看到這條巨蟒的在線圖書:http://www.cafepy.com/article/python_attributes_and_methods/ch01s05.html,它說:描述符和python提供的屬性

  1. 如果attrname是對象名特殊(即Python的提供)屬性,其返回。

我不明白Python提供的意思。有人可以給我一個這樣的Python提供的屬性的例子,它會優先於通常的解析順序嗎?

注:我只對新式課程感興趣(因爲描述符根據我所知甚至不適用於舊式課程)。

回答

0

正如你猜,第1步是完全錯誤和不存在。

1

__class__,例如:

>>> class Test(object): 
    __dict__ = {'__class__' : "dict of Test"} 
    def __init__(self): 
     self.__dict__['__class__'] = "dict of test" 


>>> test = Test() 
>>> test.__class__ 
<class '__main__.Test'> 
>>> test.__dict__ 
{'__class__': 'dict of test'} 
>>> Test.__dict__ 
dict_proxy({'__dict__': {'__class__': 'dict of test'}, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__doc__': None, '__init__': <function __init__ at 0x02BD2770>}) 
>>> 

相當於舊式類:

>>> class Test: 
     pass 

>>> Test.__dict__["__class__"] = "spam" 
>>> test = Test() 
>>> test.__class__ 
<class __main__.Test at 0x02BD1110> 
>>> test.__dict__ = {'__class__': "foo"} 
>>> test.__class__ 
<class __main__.Test at 0x02BD1110> 

>>> test.__dict__ = {'__lolcat__': "bar"} 
>>> test.__lolcat__ 
'bar' 

還有更多的特殊屬性名,這取決於對象的類型。 例如,函數:

>>> def test():pass 

>>> dir(test) 
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] 
>>> test.func_closure 
>>> test.__dict__['func_closure']='roflcopter' 
>>> test.func_closure 
>>> test.__dict__['foo']='bar' 
>>> test.foo 
'bar' 

看到http://docs.python.org/reference/datamodel.html的概述

+0

我以前沒有意識到這一點,但直接修改類的__dict__似乎不適用於新樣式的類 - 它會導致TypeError:'dict_proxy'對象不支持項目分配。您仍然可以通過修改實例的'__dict__',即'test .__ dict __ [「__ class__」] =「spam」'在python 3中看到上述行爲。另外,你知道其他屬性是如何工作的嗎?我發現的唯一另外一個是'__dict__'本身。 – James

+0

@James查看更新 – ch3ka

+0

我的問題是關於新式課程,你演示的只是舊式課程。 – Flavien