简体   繁体   English

Python类:向方法添加动态属性

[英]Python Classes: adding dynamic attributes to methods

Say we have a class: 假设我们有一个班级:

class Foo (object):
...     def __init__(self,d):
...         self.d=d
...     def return_d(self):
...         return self.d

... and a dict: ......和一个字典:

d={'k1':1,'k2':2}

... and an instance: ......和一个实例:

inst=Foo(d)

Is there a way to dynamically add attributes to return_d so: 有没有办法动态地向return_d添加属性,所以:

inst.return_d.k1 would return 1? inst.return_d.k1会返回1吗?

You'd need to do two things: declare return_d as an attribute or property, and return a dict-like object that allows attribute access for dictionary keys. 您需要做两件事:将return_d声明为属性或属性,并返回一个类似于dict的对象,该对象允许对字典键进行属性访问。 The following would work: 以下将有效:

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)

Short demo: 简短演示:

>>> foo = Foo({'k1':1,'k2':2})
>>> foo.return_d.k1
1

The property decorator turns methods into attributes, and the __getattr__ hook allows the AttributeDict class to look up dict keys via attribute access (the . operator). property装饰器将方法转换为属性, __getattr__钩子允许AttributeDict类通过属性访问( .运算符)查找dict键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM