[英]Calling a function in the dictionary in parallel with obtaining a value
I want to pass a key to a dictonary, get an attached to this key value and also call a function attached to same key if the function is present.我想将一个键传递给一个字典,得到一个附加到这个键值的值,如果 function 存在,还调用一个附加到同一个键的 function。 I'm able to create something like this
d={'some_key':('value', func())}
, but it calls the function when the dictonary is initialized.我能够创建类似这样的东西
d={'some_key':('value', func())}
,但它会在字典初始化时调用 function 。 I know that I can get a tuple with value and fucntion, check the length of this tuple and if the length equals 2 then call a function, but isn't there a more elegant way?我知道我可以获得一个具有值和功能的元组,检查这个元组的长度,如果长度等于 2,则调用 function,但是没有更优雅的方法吗? Can I somehow make the functon activate only when I input a certain key without any other syntax?
仅当我输入某个键而没有任何其他语法时,我能以某种方式使功能激活吗? Just write
d[some_key]
, get a corresponding value and execute a function without any additional brackets.只需写入
d[some_key]
,得到相应的值并执行 function,无需任何额外的括号。
You'd need to subclass dict
to override the __getitem__
method:您需要将
dict
子类化以覆盖__getitem__
方法:
class MyDict(dict):
def __getitem__(self, index):
a, b = super().__getitem__(index)
return a, b()
def myfunc():
return "Hello world"
mydict = MyDict({'a': (100, myfunc)})
print(mydict['a'])
outputs (100, 'Hello world')
输出
(100, 'Hello world')
If you want to call the function and return the value:如果要调用 function 并返回值:
class MyDict(dict):
def __getitem__(self, index):
a, b = super().__getitem__(index)
b()
return a
Note that this is very unexpected behavior, so make sure your users know what will happen when they use this dictionary.请注意,这是非常意外的行为,因此请确保您的用户知道当他们使用该词典时会发生什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.