class, dict, self, init, args?

前端 未结 3 1274
佛祖请我去吃肉
佛祖请我去吃肉 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:09

    Here's a good article that explains __dict__:

    The Dynamic dict

    The attrdict class exploits that by inheriting from a dictionary and then setting the object's __dict__ to that dictionary. So any attribute access occurs against the parent dictionary (i.e. the dict class it inherits from).

    The rest of the article is quite good too for understanding Python objects:

    Python Attributes and Methods

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 09:17

    You are not using positional arguments in your example. So the relevant code is:

    class attrdict(dict):
        def __init__(self, **kwargs):
            dict.__init__(self, **kwargs)
            self.__dict__ = self
    

    In the first line you define class attrdict as a subclass of dict. In the second line you define the function that automatically will initialize your instance. You pass keyword arguments (**kargs) to this function. When you instantiate a:

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

    you are actually calling

    attrdict.__init__(a, {'x':1, 'y':2})
    

    dict instance core initialization is done by initializing the dict builtin superclass. This is done in the third line passing the parameters received in attrdict.__init__. Thus,

    dict.__init__(self,{'x':1, 'y':2})
    

    makes self (the instance a) a dictionary:

    self ==  {'x':1, 'y':2}
    

    The nice thing occurs in the last line: Each instance has a dictionary holding its attributes. This is self.__dict__ (i.e. a.__dict__).

    For example, if

    a.__dict__ = {'x':1, 'y':2} 
    

    we could write a.x or a.y and get values 1 or 2, respectively.

    So, this is what line 4 does:

    self.__dict__ = self
    

    is equivalent to:

    a.__dict__ = a  where a = {'x':1, 'y':2}
    

    Then I can call a.x and a.y.

    Hope is not too messy.

    0 讨论(0)
提交回复
热议问题