生成动态给出字典键的方法

时间:2015-01-04 08:16:31

标签: python python-2.7 dictionary

寻找解决方案(不确定是否存在!)以下情况:
起点是字典

dict = {k1:v1, k2:v2,...,kn:vn}
其中n 已修复。
有没有办法编写一个通用类,它将动态生成n个方法,可以在下面的示例中调用:


    class example(dict):  
    example.k1()
    example.k2()
    .
    .
    .
    example.kn()

每个<{p>} example.ki() 1<=i<=n,应返回相应的vi

3 个答案:

答案 0 :(得分:4)

而不是动态创建这么多方法,而不是覆盖类的__getattr__方法,并从那里返回一个callable:

class Example(dict):
    def __getattr__(self, k):
        if k in self:
            return lambda: self[k]
        raise TypeError('Example object has not attribute {!r}'.format(k))

请注意,keys()items()等等__getattr__等密钥不会被调用,因为__getattribute__本身可以在课程中找到它们。最好不要在它们之后命名任何密钥。

演示:

>>> d = Example(a=1, b=2, c=3)
>>> d.a()
1
>>> d.b()
2
>>> d.foo()

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    d.foo()
  File "/home/ashwini/py/so.py", line 7, in __getattr__
    raise TypeError('Example object has not attribute {!r}'.format(k))
TypeError: Example object has not attribute 'foo'

答案 1 :(得分:2)

您想要覆盖__getattr__函数described here

举个例子:

class example(dict):
    def __getattr__(self, name):
        return lambda: self[name]

这允许你这样做:

e = example()
e["foo"] = 1
print e.foo()
==> 1

答案 2 :(得分:1)

我认为动态添加方法可以帮助你。

class example(object) :
            dict={'k1':'v1','k2':'v2','k3':'v3','kn':'vn'}
            def getvalue(self,key) :
                return self.dict[key]
if __name__=="__main__" :
e = example()
e.method1=e.getvalue     # this is adding a method to example class dynamically.
print e.method1('k1') 
e.method2=e.getvalue
print e.method2('k2')
e.method3=e.getvalue
print e.method3('k3')
e.methodn=e.getvalue
print e.methodn('kn')

这个输出 V1 V2 V3 VN

相关问题