简体   繁体   English

扩展内置的python dict类

[英]extending built-in python dict class

I want to create a class that would extend dict's functionalities. 我想创建一个可以扩展dict功能的类。 This is my code so far: 到目前为止,这是我的代码:

class Masks(dict):

    def __init__(self, positive=[], negative=[]):
        self['positive'] = positive
        self['negative'] = negative

I want to have two predefined arguments in the constructor: a list of positive and negative masks. 我想在构造函数中有两个预定义的参数:正掩码和负掩码的列表。 When I execute the following code, I can run 当我执行以下代码时,我可以运行

m = Masks()

and a new masks-dictionary object is created - that's fine. 并创建了一个新的masks-dictionary对象-很好。 But I'd like to be able to create this masks objects just like I can with dicts: 但我希望能够像使用字典一样创建此蒙版对象:

d = dict(one=1, two=2)

But this fails with Masks: 但这对Masks失败:

>>> n = Masks(one=1, two=2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'two'

I should call the parent constructor init somewhere in Masks. 我应该在Masks中的某个地方调用父构造函数init init probably. 初始化 I tried it with **kwargs and passing them into the parent constructor, but still - something went wrong. 我尝试使用**kwargs并将其传递给父构造函数,但仍然-出了点问题。 Could someone point me on what should I add here? 有人可以指点我在这里添加什么吗?

You must call the superclass __init__ method. 必须调用超类__init__方法。 And if you want to be able to use the Masks(one=1, ..) syntax then you have to use **kwargs : 如果您想使用Masks(one=1, ..)语法,则必须使用**kwargs

In [1]: class Masks(dict):
   ...:     def __init__(self, positive=(), negative=(), **kwargs):
   ...:         super(Masks, self).__init__(**kwargs)
   ...:         self['positive'] = list(positive)
   ...:         self['negative'] = list(negative)
   ...:         

In [2]: m = Masks(one=1, two=2)

In [3]: m['one']
Out[3]: 1

A general note: do not subclass built-ins!!! 一般注意事项: 不要将内置子类化!!! It seems an easy way to extend them but it has a lot of pitfalls that will bite you at some point. 扩展它们似乎是一种简单的方法,但是在某些时候遇到很多陷阱。

A safer way to extend a built-in is to use delegation, which gives better control on the subclass behaviour and can avoid many pitfalls of inheriting the built-ins. 扩展内置组件的一种更安全的方法是使用委托,它可以更好地控制子类的行为,并且可以避免继承内置组件的许多陷阱。 (Note that implementing __getattr__ it's possible to avoid reimplementing explicitly many methods) (请注意,实现__getattr__可以避免显式重新实现许多方法)

Inheritance should be used as a last resort when you want to pass the object into some code that does explicit isinstance checks. 当您要将对象传递给进行显式isinstance检查的代码时,应将继承用作最后的手段。

Since all you want is a regular dict with predefined entries, you can use a factory function. 由于您所需的只是带有预定义条目的常规字典,因此可以使用工厂函数。

def mask(*args, **kw):
    """Create mask dict using the same signature as dict(),
    defaulting 'positive' and 'negative' to empty lists.
    """
    d = dict(*args, **kw)
    d.setdefault('positive', [])
    d.setdefault('negative', [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM