Skip to main content
 首页 » 编程设计

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

2025年05月04日14lovecherry

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

dict = {k<sub>1</sub>:v<sub>1</sub>, k<sub>2</sub>:v<sub>2</sub>,...,k<sub>n</sub>:v<sub>n</sub>}
其中 n是 不固定的。
有没有办法编写一个具有 n 的通用类?可以在以下示例中调用的动态生成的方法:

 
    class example(dict):   
    example.k<sub>1</sub>() 
    example.k<sub>2</sub>() 
    . 
    . 
    . 
    example.k<sub>n</sub>() 

每个

example.k<sub>i</sub>()
其中 1<=i<=n , 应返回相应的 v<sub>i</sub> .

请您参考如下方法:

与其动态地创建这么多方法,不如重写类的 __getattr__ 方法并从那里返回一个可调用对象:

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__ 本身进行分类。最好不要以它们命名任何 key 。

演示:

>>> 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'