Inheritance and Overriding __init__ in python

前端 未结 5 1647
春和景丽
春和景丽 2020-12-04 06:44

I was reading \'Dive Into Python\' and in the chapter on classes it gives this example:

class FileInfo(UserDict):
    \"store file metadata\"
    def __init_         


        
5条回答
  •  不思量自难忘°
    2020-12-04 07:30

    The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.

    It looks like this nowadays:

    class FileInfo(dict):
        """store file metadata"""
        def __init__(self, filename=None):
            super(FileInfo, self).__init__()
            self["name"] = filename
    

    Note the following:

    1. We can directly subclass built-in classes, like dict, list, tuple, etc.

    2. The super function handles tracking down this class's superclasses and calling functions in them appropriately.

提交回复
热议问题