Python类中如何判断传入变量是否为指定实例变量?
问题分析
你的代码存在几个核心问题:
- 逻辑判断错误:
stat == hasattr(self, 'strength_grade')是把stat和布尔值(hasattr返回True/False)做比较,这永远不会匹配——因为stat是实例变量或变量名,和布尔值完全不是同一类型。 - 代码冗余:每个分支的逻辑完全重复,只是属性名不同,后续维护会很麻烦。
- 错误处理不当:
return print("error...")会让函数返回None(print本身无返回值),不符合返回布尔值的预期。
简洁解决方案
推荐用属性名字典映射的方式,既解决变量关联问题,又大幅简化代码:
def is_stat_enhanced(self, stat): # 建立统计量grade属性与增强标记属性的映射关系 stat_enhance_map = { 'strength_grade': self.enhanced_strength, 'endurance_grade': self.enhanced_endurance, 'agility_grade': self.enhanced_agility, 'reflex_grade': self.enhanced_reflex, 'speed_grade': self.enhanced_speed } # 尝试从映射中获取对应增强标记 enhanced_status = stat_enhance_map.get(stat) if enhanced_status is None: print("error with check enhanced") return False return enhanced_status
调用时直接传入属性名字符串即可:
# 判断力量是否增强 self.is_stat_enhanced('strength_grade')
如果确实需要传递变量本身(而非字符串),可以借助inspect模块获取变量名,但这种方式依赖调用环境,新手不推荐,实现方式如下:
import inspect def is_stat_enhanced(self, stat): # 获取调用者的局部变量,匹配传入的变量实例 caller_frame = inspect.currentframe().f_back try: # 找到对应变量的名称 stat_name = next(name for name, value in caller_frame.f_locals.items() if value is stat) except StopIteration: print("error with check enhanced") return False finally: # 释放帧对象,避免内存泄漏 del caller_frame # 从变量名中提取前缀,拼接增强标记属性名 if not stat_name.endswith('_grade'): print("error with check enhanced") return False enhance_attr_name = f'enhanced_{stat_name[:-6]}' # 返回增强标记的值,默认False return getattr(self, enhance_attr_name, False)
调用时直接传实例变量:
self.is_stat_enhanced(self.strength_grade)
额外优化建议
- 不要直接返回
print(),打印错误后返回False或抛出ValueError更合理; - 如果这些属性是固定的,可以把映射字典定义为类属性,避免每次调用都重新创建;
- 原代码中
if self.enhanced_strength == True可以简化为return self.enhanced_strength,因为属性本身就是布尔值。
内容的提问来源于stack exchange,提问作者Msr Nobody
相关产品推荐
相关产品推荐

