类,字典,自我,初始化,参数? [英] class, dict, self, init, args?
问题描述
class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
print a.x, a.y
b = attrdict()
b.x, b.y = 1, 2
print b.x, b.y
有人可以用文字解释前四行吗?我阅读了类和方法.但这里似乎很混乱.
Could somebody explain the first four lines in words? I read about classes and methods. But here it seems very confusing.
推荐答案
您没有在示例中使用位置参数.所以相关代码是:
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
在第一行中,您将 attrdict
类定义为 dict
的子类.在第二行中,您定义了将自动初始化您的实例的函数.您将关键字参数 (**kargs
) 传递给此函数.当你实例化 a
时:
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)
你实际上是在打电话
attrdict.__init__(a, {'x':1, 'y':2})
dict 实例核心初始化是通过初始化 dict
内置超类来完成的.这是在传递 attrdict.__init__
中接收到的参数的第三行中完成的.因此,
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})
使self
(实例a
)成为字典:
self == {'x':1, 'y':2}
好东西出现在最后一行:每个实例都有一个保存其属性的字典.这是self.__dict__
(即a.__dict__
).
The nice thing occurs in the last line:
Each instance has a dictionary holding its attributes. This is self.__dict__
(i.e. a.__dict__
).
例如,如果
a.__dict__ = {'x':1, 'y':2}
我们可以编写 a.x
或 a.y
并分别获得值 1 或 2.
we could write a.x
or a.y
and get values 1 or 2, respectively.
所以,这就是第 4 行所做的:
So, this is what line 4 does:
self.__dict__ = self
相当于:
a.__dict__ = a where a = {'x':1, 'y':2}
然后我可以调用 a.x
和 a.y
.
Then I can call a.x
and a.y
.
希望不要太乱.
这篇关于类,字典,自我,初始化,参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!