开发者

assign a attribute using getattr

开发者 https://www.devze.com 2023-02-07 09:05 出处:网络
I try to assign value to attributes of some calss like the following: for name in dir(modelType): if request.get(name):

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

精彩评论

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

关注公众号