Subclassing dict:should dict .__ init __()被调用? [英] Subclassing dict: should dict.__init__() be called?

查看:164
本文介绍了Subclassing dict:should dict .__ init __()被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个双重的问题,理论部分和实际的问题:



当子类化dict:



$ _ code> class ImageDB(dict):
def __init __(self,directory):
dict .__ init __(self)#必要?
...

应该 dict .__ init __(self) / code>被称为安全措施(例如,如果有一些非平凡的实施细节很重要)?如果 dict .__ init __()不是调用,那么代码是否会与Python的未来版本相冲突?我正在寻找做一件事的根本原因,在这里(实际上,调用 dict .__ init __()是安全的)。



我的猜测是当$ code> ImageDB .__ init __(self,directory)被调用时,self已经是一个新的空的dict对象,因此,不需要调用 dict .__ init __ (我首先要将dict命名为空)。这是正确的吗?



修改



以上问题如下。我正在考虑子类化dict,因为我会经常使用db [...]语法(而不是一直在做db.contents [...]);对象的唯一数据(属性)确实是一个dict。我想添加一些方法到数据库(例如 get_image_by_name() get_image_by_code(),例如),并且仅覆盖 __ init __(),因为图像数据库由包含它的目录定义。



总结,(实际)问题可能是:除了初始化不同(它只需要一个目录名称)之外,什么是行为像字典的一个很好的实现,而且它有其他方法吗?



工厂在许多答案中都提到。所以我想这一切都归结为:你是否使用dict,覆盖 __ init __()并添加方法,还是写一个返回一个dict的(factory)函数,你添加方法?我倾向于喜欢第一个解决方案,因为工厂函数返回一个对象,其类型不表示它具有附加的语义和方法,但是你觉得如何?



编辑2



我从每个人的答案中收集到,当新类不是字典时,对子类进行子类化并不是个好主意,特别是当它的 __ init __ 方法不能采用与dict的 __ init __ 相同的参数(在上面的实际问题)。换句话说,如果我理解正确,共识似乎是:当你的子类时,所有方法(包括初始化)必须具有与基类方法相同的签名。这允许isinstance(subclass_instance,dict)保证 subclass_instance .__ init __()可以像 dict .__ init __()例如。



然后弹出另一个实际问题:除了它的初始化方法之外,一个类似于dict的类应该如何实现?没有子类?这将需要一些麻烦的样板代码,否?

解决方案

你应该调用 dict .__ init __ )当子类化时;事实上,你不知道在dict中发生了什么(因为它是一个内置的),并且这些版本和实现可能会有所不同。不叫它可能会导致不正当的行为,因为你不知道dict在哪里拿着它的内部数据结构。



顺便说一句,你没有告诉我们什么你要如果你想要一个具有dict(映射)行为的类,并且你真的不需要一个dict(例如,你的软件中的任何地方都没有代码执行 isinstance(x,dict) ,因为你应该使用 UserDict.UserDict UserDict.DictMixin ,如果你'on on python< = 2.5或 collections.MutableMapping 如果你在python> = 2.6。这些将为您的课堂提供一个很好的口语行为。



编辑:我读了另一个评论,你不会超越任何dict的方法!那么根本就没有意义,不要这样做。

  def createImageDb(directory):
d = {}
#做某事填写dict
return d

编辑2:你想继承自dict来添加新的方法,但你不需要覆盖任何。比较好的选择可能是:

  class MyContainer(dict):
def newmethod1(self,args):
pass

def newmethod2(self,args2):
pass


def createImageDb(directory):
d = MyContainer )
#填写容器
返回d

顺便说一句:什么方法你在加吗你确定你创造了一个很好的抽象?也许你最好使用一个定义你需要的方法的类,并在内部使用一个正常字符串。



工厂功能:
http://en.wikipedia.org/wiki/Factory_method_pattern



这只是将实例构造委托给一个函数,而不是覆盖/更改其构造函数。


Here is a twofold question, with a theoretical part, and a practical one:

When subclassing dict:

class ImageDB(dict):
    def __init__(self, directory):
        dict.__init__(self)  # Necessary?? 
        ...

should dict.__init__(self) be called, just as a "safety" measure (e.g., in case there are some non-trivial implementation details that matter)? is there a risk that the code break with a future version of Python if dict.__init__() is not called? I'm looking for a fundamental reason of doing one thing or the other, here (practically, calling dict.__init__() is safe).

My guess is that when ImageDB.__init__(self, directory) is called, self is already a new empty dict object, and that there is therefore no need to call dict.__init__ (I do want the dict to be empty, at first). Is this correct?

Edit:

The more practical question behind the fundamental question above is the following. I was thinking of subclassing dict because I would use the db[…] syntax quite often (instead of doing db.contents[…] all the time); the object's only data (attribute) is indeed really a dict. I want to add a few methods to the database (such as get_image_by_name(), or get_image_by_code(), for instance), and only override the __init__(), because the image database is defined by the directory that contains it.

In summary, the (practical) question could be: what is a good implementation for something that behaves like a dictionary, except that its initialization is different (it only takes a directory name), and that it has additional methods?

"Factories" were mentioned in many answers. So I guess it all boils down to: do you subclass dict, override __init__() and add methods, or do you write a (factory) function that returns a dict, to which you add methods? I'm inclined to prefer the first solution, because the factory function returns an object whose type does not indicate that it has additional semantics and methods, but what do you think?

Edit 2:

I gather from everybody's answer that it is not a good idea to subclass dict when the new class "is not a dictionary", and in particular when its __init__ method cannot take the same arguments as dict's __init__ (which is the case in the "practical question" above). In other words, if I understand correctly, the consensus seems to be: when you subclass, all methods (including initialization) must have the same signature as the base class methods. This allows isinstance(subclass_instance, dict) to guarantee that subclass_instance.__init__() can be used like dict.__init__(), for instance.

Another practical question then pops up: how should a class which is just like dict, except for its initialization method, be implemented? without subclassing? this would require some bothersome boilerplate code, no?

解决方案

You should probably call dict.__init__(self) when subclassing; in fact, you don't know what's happening precisely in dict (since it's a builtin), and that might vary across versions and implementations. Not calling it may result in improper behaviour, since you can't know where dict is holding its internal data structures.

By the way, you didn't tell us what you want to do; if you want a class with dict (mapping) behaviour, and you don't really need a dict (e.g. there's no code doing isinstance(x, dict) anywhere in your software, as it should be), you're probably better off at using UserDict.UserDict or UserDict.DictMixin if you're on python <= 2.5, or collections.MutableMapping if you're on python >= 2.6 . Those will provide your class with an excellent dict behaviour.

EDIT: I read in another comment that you're not overriding any of dict's method! Then there's no point in subclassing at all, don't do it.

def createImageDb(directory):
    d = {}
    # do something to fill in the dict
    return d

EDIT 2: you want to inherit from dict to add new methods, but you don't need to override any. Than a good choice might be:

class MyContainer(dict):
    def newmethod1(self, args):
        pass

    def newmethod2(self, args2):
        pass


def createImageDb(directory):
    d = MyContainer()
    # fill the container
    return d

By the way: what methods are you adding? Are you sure you're creating a good abstraction? Maybe you'd better use a class which defines the methods you need and use a "normal" dict internally to it.

Factory func: http://en.wikipedia.org/wiki/Factory_method_pattern

It's simply a way of delegating the construction of an instance to a function instead of overriding/changing its constructors.

这篇关于Subclassing dict:should dict .__ init __()被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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