我有一个对象(从数据库检索),具有多个属性:
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/