Skip to main content
 首页 » 编程设计

python之子类化在 Python2.7 和 Python3 中具有 View 的数据类型

2024年11月01日9mfrbuaa

Python 3 引入了 View (参见 this question )。它们也被反向移植到 Python 2.7。我目前正在 Python 2.7 应用程序中对 dict 进行子类化(尽管我的目标也是将其移植到 Python 3)。我想知道是否 - 以及如何 - 我可以将 .viewitems() 和类似函数子类化,使它们的行为与原始 View 完全一样。

这是我的意图:我有一个这样的字典:

data = my_subclassed_dict 
data["_internal"] = "internal_value" 
data["key"] = "value" 
list(data.keys()) == ["key"] 

也就是说,我过滤所有以 “_” 开头的统计信息。到目前为止这工作正常:对于迭代器,我只是 yield,对于列表,我使用列表理解来过滤不需要的值。但是,这些项目不再与 dict 有任何联系(这很好,感觉就像一个 dict)。但是,这两种方式都不起作用:

keys = data.viewkeys() 
"key" in keys 
del data["key"] 
"key" not in keys # This is False ! 

最后一部分不起作用,因为没有对原始键的引用,所以 Python 不会注意到。

那么:是否有一种简单的方法来实现这一点(无需重新实现所有逻辑!)?

这更像是一个出于兴趣的问题,因为我认为它不会在我的场景中应用那么多。

请您参考如下方法:

view 对象基本上是“空”代理。他们指向原始词典。

不幸的是,当前的字典 View 对象并不是真正可重用的。引用自 source code :

/* TODO(guido): The views objects are not complete: 
 
 * support more set operations 
 * support arbitrary mappings? 
   - either these should be static or exported in dictobject.h 
   - if public then they should probably be in builtins 
*/ 

注意support arbitrary mappings条目;这些对象不支持任意映射,我们也不能从 Python 代码中创建新实例或子类:

>>> type({}.viewkeys())({}) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: cannot create 'dict_keys' instances 
>>> class MyView(type({}.viewkeys())): pass 
...  
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: Error when calling the metaclass bases 
    type 'dict_keys' is not an acceptable base type 

您被迫创建自己的并实现 View 对象支持的所有 Hook :

class DictKeys(object): 
    def __init__(self, parent): 
        self.parent = parent 
 
    def __len__(self): 
        return len(self.parent) 
 
    def __contains__(self, key): 
        return key in self.parent 
 
    def __iter__(self): 
        return iter(self.parent) 

等等

原始对象实现的方法是:

>>> dir({}.viewkeys()) 
['__and__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__ror__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__xor__'] 

__and__, __or__, __sub__, __xor__, __rand__, __ror__、__rsub__ 和 __rxor__ 方法实现了对 &、| 和 的覆盖>^ 运算符提供集合运算。

如果您在阅读 C 代码方面相当安全,请查看 view objects implementation看看他们如何实现他们的方法。