技术控

    今日:105| 主题:49390
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Python: Declaring Dynamic Attributes

[复制链接]
最妖娆。 发表于 2016-10-6 02:18:33
250 6

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
The examples below are in Python 3.5, but otherwise this post is applicable to both Python 2.x and 3.x
   It is a common solution in Python to override the __getattr__ magic method in classes, to implement dynamic attributes. Consider AttrDict - it is a dictionary that allows attribute-like access to its stored key-value pairs:
  [code]class AttrDict(dict):
    def __getattr__(self, item):
        return self[item][/code]   This simplified AttrDict allows to read dictionary values from it like attributes, but it’s pretty simple to also allow to set key-value pairs. At any rate, here it is in action:
  [code]>>> attrd = AttrDict()
... attrd["key"] = "value"
... print(attrd.key)
value[/code]   Overriding __getattr__ (and __setattr__ ) is very useful - from simple “gimmicks” like AttrDict that makes your code more readable to essential building blocks of your application like remote procedure callers (RPCs). There is, however, something a little bit frustrating about dynamic attributes - you can’t see them before you use them!
   Dynamic attributes have two usability problems when working in an interactive shell. The first is that they don’t appear when a user tries to examine the object’s API by calling the dir method:
  [code]>>> dir(attrd)  # I wonder how I can use attrd
['__class__', '__contains__', ... 'keys', 'values']
>>> # No dynamic attribute :([/code]   The second problem is autocompletion - if we set normal_attribute as an attribute the old fashioned way, we get autocompletion from most modern shell environments:
     
Python: Declaring Dynamic Attributes-1 (dynamic,attributes,dynamicattributes,declaring,declaring,class,implicitly,declaring)
     But setting dynamic_attribute by inserting it as a dictionary key-value pair does not provide us with autocompletion:

Python: Declaring Dynamic Attributes-2 (dynamic,attributes,dynamicattributes,declaring,declaring,class,implicitly,declaring)
     There is, however, an extra step you can take when implementing dynamic attributes which will make it a delight for your users and kill two birds with one stone - implement the __dir__ method . From the docs :
   If the object has a method named __dir__() , this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.
   Implementing __dir__ is straightforward: return a list of attribute names for the object:
  [code]class AttrDict(dict):
    def __getattr__(self, item):
        return self[item]

    def __dir__(self):
        return super().__dir__() + [str(k) for k in self.keys()][/code]   This will make dir(attrd) return dynamic attributes as well as the regular ones. The interesting thing about this is that  shell environments often use __dir__ to suggest autocompletion options!  so without any additional effort, we also get autocompletion:
12下一页
友荐云推荐




上一篇:Mirai “internet of things” malware from Krebs DDoS attack goes open source
下一篇:Interactive Development with Clojure.spec
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

仄y 发表于 2016-10-6 14:28:02
为了楼主,我拼了,楼下的抱紧大腿。。。
回复 支持 反对

使用道具 举报

ptyks 发表于 2016-10-7 01:24:44
支持,楼下的跟上哈~
回复 支持 反对

使用道具 举报

xundoucha 发表于 2016-11-15 11:16:42
我本非随便的人,但如果你想随便,那我就随你的便好啦!  
回复 支持 反对

使用道具 举报

安卉 发表于 2016-11-17 21:49:42
顶起~~~~
回复 支持 反对

使用道具 举报

fpwx0sOl 发表于 2016-11-19 23:21:52
贱人永远都是贱人,就算经济危机了,你也贵不了!
回复 支持 反对

使用道具 举报

钱成龙 发表于 2016-11-20 18:51:45
高手云集 果断围观
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表