开发者

assign a attribute using getattr

I try to assign value to attributes of some calss like the following:

for name in dir(modelType):
      if request.get(name):
            getattr(model, name) = request.get(name) 

but get the excption: "can't assign to functi开发者_运维知识库on call"

how can I change attributes without knowing them at complie time?


You use setattr() to assign values to attributes.

See: http://docs.python.org/library/functions.html#setattr


setattr(model, name, request.get(name))

but I'd recommend saving request data in a dictionary, dedicated class, or accessing it directly - unless you're doing specific metaprogramming/introspection, setattr is often the wrong tool for the job.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜