首页 > 解决方案 > 如果它存在于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(即最大玩家数/最大牌堆数)并返回错误。

谢谢!

标签: python

解决方案


功能方法怎么样:

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

推荐阅读