首页 > 解决方案 > 基于对象现有的 ot 或属性以更 Pythonic 的方式改进重复的 for 循环

问题描述

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

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

additionalproperty 也是一个 Object 可以为空/null/不具有所有值,在 db 中为 null 或 json

types一个数组:["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 的选项。

标签: python

解决方案


您可以使用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)  

推荐阅读