开发者

why do wrapper classes NOT inherit basic datatypes?

I was looking at the UserDict class source and I am kind of perturbed to see:

class UserDict:
  def __init__(self, dict=None, **kwargs):
    self.data = {}
    if dict is not None:
      self.update(dict)
    ...

and then methods like:

def keys(self): return self.data.keys()
def items(self): return self.data.items()
def iteritems(self): return self.data.iteritems()
def iterkeys(self): return self.data.iterkeys()
def itervalues(self): return self.data.itervalues()
def values(self): return self.data.values()  

Wouldn't it have been better to do:

class UserDict(dict):
  def __init__(self, dict=None, **kwargs):
    #self.data = {}                            # now self itself is {}
    if dict is not None:
      self.update(dict)
    ...

and then the need for aforementioned methods would simply go away.

Moreover it also helps a programmer learn on the very outset that UserDict extends the functionality of dict by looking the class d开发者_如何学Cefinition itself.


Because they're older than the ability to inherit from the basic datatypes. Modifying them to do so could have broken existing programs in various ways.


Before Python 2.2 you couldn't subclass dict. UserDict only exists for backwards compatibility.

See http://docs.python.org/library/userdict.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜