Skip to main content
 首页 » 编程设计

python之hasattr 一直返回 False

2024年10月25日14三少

class Avatar: 
 
    def __init__(self, HP=100, damage=10, defends=10, magic=5): 
        self.__hp = HP 
        self.__dam = damage 
        self.__def = defends 
        self.__mag = magic 
 
    def check_hasattr(self): 
        print hasattr(Avatar,'__hp') 
 
warrior = Avatar(99,9,9,4) 
Avatar.check_hasattr(warrior) 

有人知道为什么 print 语句返回 False 而我期望 True 吗?

请您参考如下方法:

你有两个问题:

  1. 双下划线属性名称调用“名称修改”,例如__hp 变为 _Avatar__hp(参见例如 the style guide on inheritance)。
  2. 在 check_hasattr 中,您检查 Avatar 上的属性,class,而不是 self,实例。

这会起作用:

class Avatar: 
 
    def __init__(self, HP=100, damage=10, defends=10, magic=5): 
        self.__hp = HP 
        self.__dam = damage 
        self.__def = defends 
        self.__mag = magic 
 
    def check_hasattr(self): 
        print hasattr(self, '_Avatar__hp') 

但是,没有必要保护对这些属性的访问(如果有,您应该使用 @property 而不是名称修改);参见例如Python name mangling

另请注意,Class.method(instance) 可以重写为 instance.method()。不过,在这种情况下,最简单的方法是完全删除该方法,只调用 hasattr(warrior, '_Avatar__hp')。