一个类似于dict的python类 [英] A python class that acts like dict

查看:135
本文介绍了一个类似于dict的python类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个类似于 dict 的自定义类,所以我继承自 dict 。 / p>

虽然我的问题是:我需要在我的 dict > __ init __()方法?我没有看到这一点,因为如果我只是继承自 dict ,我已经有了 dict 行为。



任何人都可以指出大部分的继承片段如下图所示:

 code> class CustomDictOne(dict):
def __init __(self):
self._mydict = {}

#其他方法跟随

而不是简单的...

  class CustomDictTwo(dict):
def __init __(self):
#初始化我的其他东西在这里...

#其他方法跟着

其实,我想我怀疑问题的答案是让用户不能直接访问你的字典(即他们必须使用



但是,数组访问运算符 [] 如何?一个如何实现?到目前为止,我还没有看到一个例子,显示如何覆盖 [] 运算符。



所以如果自定义类中没有提供 [] 访问功能,那么继承的基本方法将会运行在不同的字典上?



我尝试了以下代码段来测试我对Python继承的理解:

  class myDict(dict):
def __init __(self):
self._dict = {}

def add(self,id,val )
self._dict [id] = val


md = myDict()
md.add('id',123)
print md [id]

我收到以下错误:


KeyError:<内置函数id>


上面的代码有什么问题?



如何更正课程 myDict ,以便我可以编写这样的代码?

  md = myDict()
md ['id'] = 123



我已经编辑了上面的代码示例,以摆脱我在我的桌子之外摆脱的愚蠢错误。这是一个错字(我应该从错误信息中发现)。

解决方案

检查模拟容器类型。在您的情况下,添加的第一个参数应为 self


I want to write a custom class that behaves like dict - so, I am inheriting from dict.

My question, though, is: Do I need to create a private dict member in my __init__() method?. I don't see the point of this, since I already have the dict behavior if I simply inherit from dict.

Can anyone point out why most of the inheritance snippets look like the one below?

class CustomDictOne(dict):
   def __init__(self):
      self._mydict = {} 

   # other methods follow

Instead of the simpler...

class CustomDictTwo(dict):
   def __init__(self):
      # initialize my other stuff here ...

   # other methods follow

Actually, I think I suspect the answer to the question is so that users cannot directly access your dictionary (i.e. they have to use the access methods that you have provided).

However, what about the array access operator []? How would one implement that? So far, I have not seen an example that shows how to override the [] operator.

So if a [] access function is not provided in the custom class, the inherited base methods will be operating on a different dictionary?

I tried the following snippet to test out my understanding of Python inheritance:

class myDict(dict):
    def __init__(self):
        self._dict = {}

    def add(self, id, val):
        self._dict[id] = val


md = myDict()
md.add('id', 123)
print md[id]

I got the following error:

KeyError: < built-in function id>

What is wrong with the code above?

How do I correct the class myDict so that I can write code like this?

md = myDict()
md['id'] = 123

[Edit]

I have edited the code sample above to get rid of the silly error I made before I dashed away from my desk. It was a typo (I should have spotted it from the error message).

解决方案

Check the documentation on emulating container types. In your case, the first parameter to add should be self.

这篇关于一个类似于dict的python类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆