[英]Python - Dictionary - Modify __getitem__?
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: 好的,所以我构建了自己的变量处理程序,它具有
__getitem__
函数,可以在通过数据[key]访问数据时使用,除了在尝试访问项目链接时,它的效果很好:
data["key"]["subkey"]
def __getitem__(self, key, **args):
print key
...
return self.dict[key]
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? 当试图访问一个不存在的子键时,Python只返回一个KeyError而不打印“subkey”,为什么会这样,我怎样才能让Python打印出我实际想要获得的内容?
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
...
The goal is to emulate the following, 目标是模仿以下,
Works: 作品:
data = {'key' : {'subkey' : 1}}
print data["key"]["subkey"]
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: 将无法工作,但我想在
__getitem__
捕获异常,然后自动创建缺失的密钥或只记录丢失的子密钥:
data = {'key' : {}}
print data["key"]["subkey"]
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']
Output: 输出:
: test
:测试
: down
: 下
None
没有
The fact is that when Python encounters an expression such as data["key"]["subkey"]
, what is done internally is (data["key"])["subkey"]
. 事实是,当Python遇到诸如
data["key"]["subkey"]
类的表达式时,内部完成的是(data["key"])["subkey"]
。 That is, the first part of the expression is resolved: the retrievalof the item "key" from the object "data". 也就是说,表达式的第一部分被解决:从对象“data”中检索项“key”。 Then, Python tries do call
__getitem__
on the resulting object of that expression. 然后,Python尝试在该表达式的结果对象上调用
__getitem__
。 If such resulting object does not have a __getitem__
method itself, there is your error. 如果这样的结果对象本身没有
__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. 有两种可能的解决方法:你应该使用“元组索引” - 比如
data["key", "subkey"]
(然后测试你的__getitem__
方法,你得到一个元组实例作为键) - 或者使__getitem__
返回一个也具有__getitem__
方法的专用对象 - 即使它只是记录所请求的密钥。
Remember: tmp = foo['bar']['baz']
is the same as tmp = foo['bar']; tmp = tmp['baz']
请记住:
tmp = foo['bar']['baz']
与tmp = foo['bar']; tmp = tmp['baz']
tmp = foo['bar']; tmp = tmp['baz']
So to allow arbitrary depths your __getitem__
method must return a new object that also contains such a __getitem__
method. 因此,为了允许任意深度,
__getitem__
方法必须返回一个也包含这样一个__getitem__
方法的新对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.