kwargs重写dict子类

2024-06-26 14:26:17 发布

您现在位置:Python中文网/ 问答频道 /正文

一个最小的例子如下:

class sdict(dict):
    class dval:
        def __init__(self, val):
            self.val = val

    def __init__(self, args):
        dictionary = dict(args)
        for k,v in dictionary.items():
            self[k] = v

    def __setitem__(self,key,value):
         try:                   self[key].val = value
         except KeyError:       dict.__setitem__(self,key,self.dval(value))
    def __getitem__(self,key):
         return dict.__getitem__(self,key).val

现在我可以在容器中使用这个类来重写赋值内容:

^{pr2}$

我使用这个方法是为了让我的容器保存一个带有可点原语的字典(即python语言中的mutable),但是每当我检索到条目时,我都会得到原语本身。在我的情况下,浮动,我乘,加等等。。。在打印这些函数时,添加u str_u/u repr_uu函数可以使其正常工作,但出于调试目的,这些函数被省略了。在

这几乎在任何地方都能很好地工作,除非使用kwargs传递:

def test(a,b): return a*b
c = cont()
c.mydict = {'a':1,'b':2}
print c.mydict['a']+c.mydict['b'],type(c.mydict['a']+c.mydict['b'])
print test(**c.mydict)

输出:

3 <type 'int'>
Traceback (most recent call last):
  File "D:\kabanus\workspace\py-modules\test.py", line 32, in <module>
    print test(**c.mydict)
  File "D:\kabanus\workspace\py-modules\test.py", line 28, in test
    def test(a,b): return a*b
TypeError: unsupported operand type(s) for *: 'instance' and 'instance'

显然,解包过程并没有使用ugetitem_uu为关键字创建值。我还试图重写values()和items(),但没有成功。接下来,我将所有未定义的dict方法设置为None,以查看是否调用了任何dict方法-也没有成功。在

底线-如何让**kwargs解包以使用\uugetitem_uu或其他方法?
这有可能吗?在

如果可能的话,我还希望避免在类dval中定义mul、add、div等。在


Tags: 方法key函数inpytestselfreturn
1条回答
网友
1楼 · 发布于 2024-06-26 14:26:17

在这里找到了答案,应该有一种方法可以更容易地找到: Does argument unpacking use iteration or item-getting?

小结: 从内置函数(dict,list…)继承是有问题的,因为python可能会完全忽略python API(就像它对我所做的那样)而使用底层C。这发生在参数解包中。在

解决方案:使用可用的摘要。在我的示例中添加:

from UserDict import UserDict

并用UserDict替换代码中出现的所有“dict”。对于列表和元组,这个解决方案应该是正确的。在

相关问题 更多 >