roo*_*oot 2 python attributes class
假设我们有一个班级:
class Foo (object):
... def __init__(self,d):
... self.d=d
... def return_d(self):
... return self.d
Run Code Online (Sandbox Code Playgroud)
......和一个字典:
d={'k1':1,'k2':2}
Run Code Online (Sandbox Code Playgroud)
......和一个实例:
inst=Foo(d)
Run Code Online (Sandbox Code Playgroud)
有没有办法动态添加属性return_d:
inst.return_d.k1 会回1吗?
您需要做两件事:声明return_d为属性或属性,并返回一个类似于dict的对象,允许对字典键进行属性访问.以下将有效:
class AttributeDict(dict):
__getattr__ = dict.__getitem__
class Foo (object):
def __init__(self,d):
self.d=d
@property
def return_d(self):
return AttributeDict(self.d)
Run Code Online (Sandbox Code Playgroud)
简短演示:
>>> foo = Foo({'k1':1,'k2':2})
>>> foo.return_d.k1
1
Run Code Online (Sandbox Code Playgroud)
所述property装饰变成方法分成属性,并且__getattr__钩允许AttributeDict类通过属性访问(所述查找字典键.操作者).