有什么技巧可以“重载点运算符”吗?
我知道这个问题的表述有点奇怪,但我想不出任何其他方式来表达。我有一个处理大型 json 对象的应用程序,我希望能够只是说:
object1.value.size.whatever.attributexyz
而不是
object1.get('value').get('size').get('whatever').get('attributexyz')
有一些聪明的方法来捕获将引发的 AttributeError 并检查数据结构内部是否该属性对应于它的任何值?
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
instead of
object1.get('value').get('size').get('whatever').get('attributexyz')
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在
object1
的类定义中,任何解析对象本身实际不存在的属性、方法或字段名称的尝试都将传递给
__getattr__
。如果您无权访问类定义,即它类似于字典,请将其包装在类中。对于字典,您可以执行以下操作:
请注意,如果键无效,将引发 KeyError;然而,约定是引发 AttributeError (谢谢,S. Lott!)。如有必要,您可以将 KeyError 重新引发为 AttributeError,如下所示:
另请记住,如果从 __getattr__ 返回的对象也是字典,则您也需要包装它们。
In
object1
's class definition,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:
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:
Also remember that if the objects you are returning from
__getattr__
are also, for example, dictionaries, you'll need to wrap them too.使用定义的
__getattr__()
方法将结构包装在对象中。如果您对该结构有任何控制权,则可以定义其自己的__getattr___()
。 Getattr 正是您想要的 - “捕获”丢失的属性并可能返回一些值。Wrap the structure in an object with adefined
__getattr__()
method. If you have any control over the structure you can define its own__getattr___()
. Getattr does just what you want - "catches" missing attributes and possibly returns some value.我想做同样的事情,就开始尝试并想出了一个可以做同样事情的类(如下)。
它可能不是最漂亮的东西,但它确实有效。
示例
json.loads() 的 结果实际上是一个字典或列表,因此您可以使用该调用的返回结果。例如,传入一个字典并在使用它之前检查属性是否存在。 :
班级
I was wanting to do the same thing and just started playing around and came up with a class (below) that would do the same thing.
It might not be the prettiest thing, but it does work.
Example
Results of a json.loads() is effectively a dict or list, so you can use the return from that call. As an example, pass in a dict and check if a property is there before using it. :
Class
只是用一个例子来补充上述答案。
输出,
Just to complement the above answers with a example.
outputs,