python - 基于对象现有的 ot 或属性以更 Pythonic 的方式改进重复的 for 循环
问题描述
我有一个对象(从数据库中检索),具有多个属性:
db_obj.default_attr= "textdefault"
db_obj.additional = {
"alpha": "texta",
"beta": "textb",
"gama": "textg",
"teta": "textt",
...
}
db_obj.name: "some_name"
....
additional
property 也是一个 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 的选项。
解决方案
您可以使用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)
推荐阅读
- websocket - 在 Jetty 9.2.13.v20150730 上使用 Web 套接字部署项目时出现问题
- linux - 如何在 Linux 中使用 tail 但忽略子目录
- python - 如何从列列表中创建新列
- javascript - 反向在 JSFiddle 中有效,但在 html 文件中无效
- google-chrome - 是否可以让谷歌扩展清单 3 的后台 js 保持活动状态?
- c# - 在 EF Core 中使用表达式树会产生奇怪的 SQL 语句
- discord - 更改设置而不更改代码
- php - 错误:预期的已知函数,在 symfony3.4 上得到 'CURDATE'
- shopify - 从 Shopify 数据层获取数量值
- linux - 如果提供的密码正确,bash/expect 脚本将继续