Python - 词典 - 修改__getitem__? [英] Python - Dictionary - Modify __getitem__?

查看:158
本文介绍了Python - 词典 - 修改__getitem__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我建立了自己的变量处理程序,它有一个 __ getitem __ 函数,用于通过数据[key]访问数据时,它的工作原理很好,除了尝试访问项目的链接:

Ok so i've build my own variable handler which has a __getitem__ function for use when accessing data via data[key], it works great except for when trying to access a link of items:

data["key"]["subkey"]


def __getitem__(self, key, **args):
    print key
    ...
    return self.dict[key]

当尝试访问不存在的子项时,Python只需返回一个KeyError而不打印子键,为什么会这样,如何获取Python打印出我实际想要的东西?

When trying to access a subkey that doesn't exist, Python simply returns a KeyError without printing "subkey", why is this and how can I get Python to print out what I'm actually trying to get?

我知道我可能误解了力学,但是有一种模拟字典的方式,并按照字符串正在请求的数据?
主要是我可以动态地记录一个字典流中的缺失变量...

I know that I've probably misunderstood the mechanics but is there a way to emulate a dictionary AND follow the string of data that's being requested? Mainly so I can dynamically log the missing variables in a dictionary flow...

这显然有效(但它不是我喜欢的本机语法):

This obviously works (but it's not the native syntax that I like):

data["key:subkey"]

def __getitem__(self, key, **args):
    for slice in key.split(':'):
        print key
    ...

目标是模拟以下内容,

作品:

data = {'key' : {'subkey' : 1}}
print data["key"]["subkey"]

将无法正常工作,但我想在 __ getitem __ 中捕获异常,然后创建缺少的键自动或只是记录缺少的子项:

Will not work, but I want to catch the exception within __getitem__ and then create the missing key automatically or just log the missing subkey:

data = {'key' : {}}
print data["key"]["subkey"]






解决方案:


Solution:

class Var():
    def __init__(self):
        self.dict = {'test' : {}}
    def __getitem__(self, var, **args):
        print ':',var
        if var in self.dict:
            v = Var(self.dict[var])
            return v

print vHandle['test']['down']

输出:


:test

: test

:down


推荐答案

事实是,当Python遇到一个表达式,例如 data [key] [subkey] ,内部完成的是(data [key])[ 子项] 。也就是说,表达式的第一部分被解决:从对象数据中检索项目key。然后,Python尝试在该表达式的结果对象上调用 __ getitem __
如果这样的结果对象没有一个 __ getitem __ 方法本身就有错误。

The fact is that when Python encounters an expression such as data["key"]["subkey"], what is done internally is (data["key"])["subkey"]. That is, the first part of the expression is resolved: the retrievalof the item "key" from the object "data". Then, Python tries do call __getitem__ on the resulting object of that expression. If such resulting object does not have a __getitem__method itself, there is your error.

是两种可能的解决方法:你应该使用tuple索引,如
data [key,subkey] (然后测试你的 __ getitem __ 方法,你有一个元组实例作为键) - 或使 __ getitem __ 返回一个还具有 __ getitem __ 方法 - 即使它所做的一切都是记录所请求的密钥。

There are two possible workarounds there: you should either work with "tuple indexes" - like data["key", "subkey"](and then test on your __getitem__ method wether you got a tuple instance as the key) - or make __getitem__ return an specialized object that also features a __getitem__ method - even if all it does is to log the requested keys.

这篇关于Python - 词典 - 修改__getitem__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆