2

I am new to programming and I came across this piece of code in the following thread: Assign function arguments to `self`

class C(object):
      def __init__(self, **kwargs):
             self.__dict__ = dict(kwargs)
c = C(g="a",e="b",f="c")
print(c.g,c.e,c.f)

Output:
a b c

This would allow inputting any number of keyword arguments and assign them to attributes accordingly.

My questions are:

  1. Why does it work? What does self.__dict__ do here?
  2. Is there any other usage of self.__dict__?

I would also appreciate any kind of resources that could help me understand it. Thank you in advance.

  • https://stackoverflow.com/a/19907498/764182 – Dmitry Belaventsev Nov 22 '20 at 07:54
  • Does this answer your question? [What is the \_\_dict\_\_.\_\_dict\_\_ attribute of a Python class?](https://stackoverflow.com/questions/4877290/what-is-the-dict-dict-attribute-of-a-python-class) – Ruli Nov 22 '20 at 08:50

2 Answers2

0
Here **kwargs represent one can take any number of parameters.  
    
c = C(g="a",e="b",f="c") means that:  
variable g = "a" 
variable e = "b" 
variable f = "c"
    
Here self.__ dict __ contains the dictionary as: {g: "a", e: "b", f:"c"}

  __ dict __ is A dictionary or other mapping object used to store an object’s (writable) attributes.  

  Or speaking in simple words every object in python has an attribute which is denoted by __ dict __.  
   
 And this object contains all attributes defined for the object. __ dict __ is also called mappingproxy object.
Yashi
  • 1
  • 1
0

self.dict is a dictionary which contains key value pairs of a particular object and its attributes.It is generally used for listing out all the attributes and its values of a particular object.

In this example self.dict is {g:"a",e:"b",f:"c"}

**kwargs is used when we don't know how many keyword arguments are given when the object is created.So,converting kwargs into a dictionary and assigning it to the self.dict is same as creating all the attributes and setting their values.