伪字典作为属性
我有一个Python类C
,它应该有两个伪dict
s a
和b
。术语“伪字典”意味着字典实际上并不存在,并且每次访问键时都会“重新计算”它们。
在伪代码中,这看起来像这样:
class C:
def a.__getitem__(self, key):
return 'a'
def b.__getitem__(self, key):
return 'b'
>>> c = C()
>>> c.a['foo']
'a'
>>> c.b['bar']
'b'
我可以为 a
和 b
实现一个类,但由于两者都只有一些简短的方法,我想知道是否有一个更优雅的方法和紧凑的方式来做到这一点。
I have a Python class C
which should have two pseudo-dict
s a
and b
. The term pseudo-dicts means that the dictionaries don't actually exist and that they are “recomputed” each time a key is accessed.
In pseudocode this would look like this:
class C:
def a.__getitem__(self, key):
return 'a'
def b.__getitem__(self, key):
return 'b'
>>> c = C()
>>> c.a['foo']
'a'
>>> c.b['bar']
'b'
I could implement a class for a
and b
, but since both have just a few short methods, I wonder whether there is a more elegant and compact way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么不定义自己的类呢?
我不确定这些“伪字典”的值来自哪里,因此您必须更新
__getitem__
方法。Why not just define your own class?
I'm not sure where the values for these 'pseudo-dicts' are coming from, so you'll have to update the
__getitem__
method.像这样?
或者对于真正的计算函数来说可能像这样?
Like this?
Or maybe like this for real calculation functions?