class, dict, self, init, args?

前端 未结 3 1279
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 08:45
class attrdict(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(self, *args, **kwargs)
        self.__dict__ = self

a = attrdict(x=1, y=2)
prin         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-30 09:10

    My shot at a line-by-line explanation:

    class attrdict(dict):
    

    This line declares a class attrdict as a subclass of the built-in dict class.

    def __init__(self, *args, **kwargs): 
        dict.__init__(self, *args, **kwargs)
    

    This is your standard __init__ method. The call to dict.__init__(...) is to utilize the super class' (in this case, dict) constructor (__init__) method.

    The final line, self.__dict__ = self makes it so the keyword-arguments (kwargs) you pass to the __init__ method can be accessed like attributes, i.e., a.x, a.y in the code below.

    Hope this helps clear up your confusion.

提交回复
热议问题