Python OOP自动分配关键字参数



我是编程新手,在以下线程中遇到了这段代码:将函数参数分配给"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

这将允许输入任意数量的关键字参数,并相应地将它们分配给属性。

我的问题是:

  1. 为什么它有效?self.__dict__在这里做什么
  2. self.__dict__还有其他用途吗

我也很感激任何能帮助我理解它的资源。提前谢谢。

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.

selfdict是一个字典,它包含特定对象及其属性的键值对。它通常用于列出特定对象的所有属性及其值。

在这个例子中是自我dict是{g:"a",e:"b",f:"c"}

**当我们不知道创建对象时给出了多少关键字参数时,就会使用kwargs。因此,将kwargs转换为字典并将其分配给selfdict与创建所有属性并设置其值相同。

最新更新