python - 基于对象现有的 ot 或属性,以更 Pythonic 的方式改进重复的 for 循环

标签 python

我有一个对象(从数据库检索),具有多个属性:

db_obj.default_attr= "textdefault"
 db_obj.additional = {
    "alpha": "texta",
    "beta": "textb",   
    "gama": "textg",
    "teta": "textt",
     ...
}
 db_obj.name: "some_name"
 .... 

additional 属性也是一个对象,可以是空/null/不具有所有值,在 db 中为 null 或 json

并且类型一个数组:["alpha", "gama", ...]


我有以下函数,称为:

set_att(obj=db_object, types=types)

我需要基于types数组创建一个新对象:

属性示例:

  new_obj.alpha = "texta"
  new_obj.gama =  "textdefault"  # because gama was not found in additional

我定义了这个函数:

def set_att(db_obj=None, types=None):

 new_obj = types.SimpleNamespace()

try:

  add = db_obj.getattr(additional)

  # cycle thru types, and assign the value from the db_obj if exist or the     default_attr value
  for item_type in types: 
     try:
        setattr(new_obj, item_type, add.getattr(item_type))
      except AttributeError: 
         setattr(new_obj, item_type, obj.getattr(default_attr))   

 # if there is not addtional I still set default for type
except AttributeError:
    for item_type in types: 
         setattr(new_obj, item_type, obj.getattr(default_attr)

它看起来很天真,我正在寻找一个更Pythonic的选项。

最佳答案

您可以使用hasattr来检查对象是否具有属性,而不是捕获AttributeException。它将使代码更易于阅读,因为它显式处理属性不存在的预期情况。使用异常会使它看起来像是一个错误情况。

 for item_type in types:
     if hasattr(add, item_type):
         value = getattr(add, item_type) 
     else:
         value = getattr(obj, default_attr)
     setattr(new_obj, item_type, value)  

关于python - 基于对象现有的 ot 或属性,以更 Pythonic 的方式改进重复的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54792041/

相关文章:

python - PyYAML 内存泄漏

python - 从弹出窗口获取文本

python - 错误 : too many values to unpack

python - Python 中的字符格式化

python - 在以交互模式运行脚本之前,如何将脚本传递给 Sage?

python - pandas 仅替换列的一部分

python - 迭代整数的 Pythonic 或最佳实践方法是什么?

python - 使用 Python 的 FTP 库检索文件

python - Keras 将功能模型转换为模型子类

python - 将 mysql select 语句的输出存储为 python 列表