【问题标题】:Python OOP Auto Assigning Keyword ArgumentsPython OOP 自动分配关键字参数
【发布时间】:2020-11-22 07:48:19
【问题描述】:
我是编程新手,我在以下线程中遇到了这段代码:
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
这将允许输入任意数量的关键字参数并相应地将它们分配给属性。
我的问题是:
- 为什么会起作用?
self.__dict__ 在这里做什么?
-
self.__dict__还有其他用法吗?
我也很感激任何可以帮助我理解它的资源。提前谢谢你。
【问题讨论】:
标签:
python
dictionary
oop
【解决方案1】:
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.
【解决方案2】:
self.dict是一个包含特定对象及其属性的键值对的字典。它通常用于列出特定对象的所有属性及其值。
在这个例子中 self.dict 是 {g:"a",e:"b",f:"c"}
**kwargs 用于当我们不知道创建对象时给出了多少关键字参数时。因此,将kwargs转换为字典并将其分配给自身。dict是相同的就像创建所有属性并设置它们的值一样。