请选择 进入手机版 | 继续访问电脑版

技术控

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

[其他] Python: Declaring Dynamic Attributes

[复制链接]
最妖娆。 发表于 2016-10-6 02:18:33
378 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:
  1. class AttrDict(dict):
  2.     def __getattr__(self, item):
  3.         return self[item]
复制代码
  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:
  1. >>> attrd = AttrDict()
  2. ... attrd["key"] = "value"
  3. ... print(attrd.key)
  4. value
复制代码
  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:
  1. >>> dir(attrd)  # I wonder how I can use attrd
  2. ['__class__', '__contains__', ... 'keys', 'values']
  3. >>> # No dynamic attribute :(
复制代码
  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

Python: Declaring Dynamic Attributes
     But setting dynamic_attribute by inserting it as a dictionary key-value pair does not provide us with autocompletion:
     

Python: Declaring Dynamic Attributes

Python: Declaring Dynamic Attributes
     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:
  1. class AttrDict(dict):
  2.     def __getattr__(self, item):
  3.         return self[item]
  4.     def __dir__(self):
  5.         return super().__dir__() + [str(k) for k in self.keys()]
复制代码
  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:
     

Python: Declaring Dynamic Attributes

Python: Declaring Dynamic Attributes
     ThankstoRam Rachum for reading drafts of this.



上一篇: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-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表