|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
关于这个函数的功能实现,各位大神能帮我解释一下么?谢谢啦
class Bunch(dict):
"""Container object for datasets
Dictionary-like object that exposes its keys as attributes.
>>> b = Bunch(a=1, b=2)
>>> b['b']
2
>>> b.b
2
>>> b.a = 3
>>> b['a']
3
>>> b.c = 6
>>> b['c']
6
"""
def __init__(self, **kwargs):
super(Bunch, self).__init__(kwargs)
def __setattr__(self, key, value):
self[key] = value
def __dir__(self):
return self.keys()
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(key)
def __setstate__(self, state):
# Bunch pickles generated with scikit-learn 0.16.* have an non
# empty __dict__. This causes a surprising behaviour when
# loading these pickles scikit-learn 0.17: reading bunch.key
# uses __dict__ but assigning to bunch.key use __setattr__ and
# only changes bunch['key']. More details can be found at:
# https://github.com/scikit-learn/scikit-learn/issues/6196.
# Overriding __setstate__ to be a noop has the effect of
# ignoring the pickled __dict__
pass
首先你实例化这个类 b = Bunch(a=1, b=2)
类初始化的时候
def __init__(self, **kwargs):
super(Bunch, self).__init__(kwargs)
super函数会自动寻找基类的同名函数__init__
因为参数kwargs 为 a=1, b=2
所以在在进行保存操作的时候
def __setattr__(self, key, value):
self[key] = value
就会设置属性a=1 b=2
b["b"] 以及b.b都是访问类属性b 所以返回2
b.a = 3 就是设置b的类属性a 的值为3
所以b['a'] 返回3
b.['c'] = 6 就是添加一个新的类属性 c 值为6
因此b["c"] 返回6
|
|