python - 如果它存在于Python中,如何附加类的属性值
问题描述
我正在尝试制作一个特定的棋盘游戏,但在查找变量“to”和“play”中是否存在属性时遇到了一些麻烦
index_error_lst = []
if hasattr(play, 'player_no'):
index_error_lst.append(play.discard_pile_no)
if hasattr(play, 'player_no'):
index_error_lst.append(play.player_no)
if hasattr(to, 'discard_pile_no'):
index_error_lst.append(to.discard_pile_no)
if hasattr(to, 'build_pile_no'):
index_error_lst.append(to.build_pile_no)
if hasattr(to, 'player_no'):
index_error_lst.append(to.player_no)
if sorted(index_error_lst)[-1] > 3:
return 0
我觉得这种方法是检查类中是否存在属性的一种非常冗长且乏味的方法。有没有办法通过属性进行for循环检查并附加那些存在并继续那些不存在的?
最后两行用于检查 index_error_lst 并查看这些属性中的任何数字是否大于 3(即最大玩家数/最大牌堆数)并返回错误。
谢谢!
解决方案
功能方法怎么样:
from itertools import product
# ...
index_error_lst = filter(
# Filter out not-found or None values
lambda value: value is not None,
map(
# Will receive tuple (obj, attr)
# Attempt to get the value or fallback to None
lambda attr: getattr(attr[0], attr[1], None),
# Cartesian product of its arguments
product(
(play, to),
('player_no', 'discard_pile_no', 'build_pile_no')
)
)
)
# ...
if any(value > 3 for value in index_error_lst):
return 0
推荐阅读
- python - 是否有一种 Pythonic 方式来创建克隆项目列表?
- php - Laravel / Artisan CLI 重置 error_reporting 级别?
- javascript - 如何使用 javascript jquery 关闭父 div
- r - 如何使用字符串作为函数的正式形式运行函数?
- azure - Azure 存储队列最大并发客户端数
- sql - 从查询中获取 2019 年结果
- django - 调试工具栏 django 未执行
- c# - 传入字典的模型项在我的代码中属于类型错误
- javascript - 尝试将事件从其组件之一传播到自定义 HTML 元素会抛出
- node.js - 如何在nodejs中使用openssl生成公钥/私钥对?