相关疑难解决方法(0)

如何动态地向类添加属性?

目标是创建一个类似于db结果集的模拟类.

因此,例如,如果数据库查询使用dict表达式返回{'ab':100, 'cd':200},那么我想看到:

>>> dummy.ab
100
Run Code Online (Sandbox Code Playgroud)

起初我想也许我可以这样做:

ks = ['ab', 'cd']
vs = [12, 34]
class C(dict):
    def __init__(self, ks, vs):
        for i, k in enumerate(ks):
            self[k] = vs[i]
            setattr(self, k, property(lambda x: vs[i], self.fn_readyonly))

    def fn_readonly(self, v)
        raise "It is ready only"

if __name__ == "__main__":
    c = C(ks, vs)
    print c.ab
Run Code Online (Sandbox Code Playgroud)

但是c.ab返回一个属性对象.

更换setattr线路k = property(lambda x: vs[i])完全没用.

那么在运行时创建实例属性的正确方法是什么?

PS我知道如何__getattribute__使用该方法?

python monkeypatching runtime properties

193
推荐指数
11
解决办法
19万
查看次数

如何在__init__中定义属性

我想从成员函数中定义类中的属性.下面是一些测试代码,显示了我希望如何工作.但是我没有得到预期的行为.

class Basket(object):

  def __init__(self):
    # add all the properties
    for p in self.PropNames():
      setattr(self, p, property(lambda : p) )

  def PropNames(self):
    # The names of all the properties
    return ['Apple', 'Pear']

  # normal property
  Air = property(lambda s : "Air")

if __name__ == "__main__":
  b = Basket()
  print b.Air # outputs: "Air"
  print b.Apple # outputs: <property object at 0x...> 
  print b.Pear # outputs: <property object at 0x...> 
Run Code Online (Sandbox Code Playgroud)

我怎么能让这个工作?

python constructor properties

5
推荐指数
1
解决办法
3425
查看次数