2012-05-10 61 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