有什么技巧可以“重载点运算符"吗? [英] Is there any trick to "overload the dot operator"?
问题描述
我知道这个问题有点奇怪,但是我想不出其他任何方式来表达.我有一个处理大型json对象的应用程序,我希望能够说:
I know the question is a little weirdly stated, but I can't think of any other way of saying it. I have an application that deals with large json objects, and I want to be able to just say:
object1.value.size.whatever.attributexyz
代替
object1.get('value').get('size').get('whatever').get('attributexyz')
是否有一些聪明的方法来捕获将要引发的AttributeError
并检查数据结构内部的属性是否对应于其任何值?
Is there some clever way to catch the AttributeError
that would be raised and check inside the data structure if that attribute corresponds to any of its values?
推荐答案
在object1
的类定义中,
def __getattr__(self, key):
return self.get(key)
任何尝试解析对象本身上实际上不存在的属性,方法或字段名称的尝试都将传递给
Any attempt to resolve a property, method, or field name that doesn't actually exist on the object itself will be passed to __getattr__
.
如果您无权访问类定义,即类似于字典,则将其包装在类中.对于字典,您可以执行以下操作:
If you don't have access to the class definition, i.e. it's something like a dictionary, wrap it in a class. For a dictionary, you could do something like:
class DictWrapper(object):
def __init__(self, d):
self.d = d
def __getattr__(self, key):
return self.d[key]
请注意,如果密钥无效,则会引发KeyError;否则,将引发KeyError.但是,约定是引发AttributeError(感谢S. Lott!).您可以像这样重新引发KeyError作为AttributeError:
Note that a KeyError will be raised if the key is invalid; the convention, however, is to raise an AttributeError (thanks, S. Lott!). You can re-raise the KeyError as an AttributeError like so, if necessary:
try:
return self.get(key)
except KeyError as e:
raise AttributeError(e)
还请记住,如果您从__getattr__
返回的对象也是字典,那么您也需要将它们包装起来.
Also remember that if the objects you are returning from __getattr__
are also, for example, dictionaries, you'll need to wrap them too.
这篇关于有什么技巧可以“重载点运算符"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!