python: inheriting or composition

后端 未结 4 1203
夕颜
夕颜 2021-02-05 13:40

Let\'s say that I have class, that uses some functionality of dict. I used to composite a dict object inside and provide some access from

4条回答
  •  借酒劲吻你
    2021-02-05 13:54

    Both are good, but I'd prefer inheriting, as it will mean less code (which is always good as long as it is readable).

    Dive into Python has a very relevant example.

    On Python 2.2 and prior, you couldn't subclass from built ins directly, so you had to use composition.

    class FileInfo(dict):                  
       "store file metadata"
       def __init__(self, filename=None): 
           self["name"] = filename
    
    1. The first difference is that you don't need to import the UserDict module, since dict is a built-in datatype and is always available. The second is that you are inheriting from dict directly, instead of from UserDict.UserDict.
    2. The third difference is subtle but important. Because of the way UserDict works internally, it requires you to manually call its __init__ method to properly initialize its internal data structures. dict does not work like this; it is not a wrapper, and it requires no explicit initialization.

提交回复
热议问题