Discuss / Python / hasattr(geyuanyuan,'__age')的结果是False,不是True

hasattr(geyuanyuan,'__age')的结果是False,不是True

Topic source

NightWatch2

#1 Created at ... [Delete] [Delete and Lock User]
class MyObject(object):
    def __init__(self):
        self.x = 9
    def power(self):
        return self.x * self.x 

obj = MyObject() 

print('hasattr(obj, \'x\') =', hasattr(obj, 'x')) # 有属性'x'吗?

class MyObject1(object):
    def __init__(self):
        self.__x = 9
    def power1(self):
        return self.__x * self.__x 

obj1 = MyObject1() 

print('hasattr(obj1, \'x\') =', hasattr(obj, 'x')) # 有属性'x'吗?
print('hasattr(obj1, \'__x\') =', hasattr(obj1, '__x')) # 有属性'__x'吗?
print('hasattr(obj1, \'_MyObject1__x\') =', hasattr(obj1, '_MyObject1__x')) # 有属性'_MyObject1__x'吗?

结果是
hasattr(obj, 'x') = True
hasattr(obj1, 'x') = True
hasattr(obj1, '__x') = False
hasattr(obj1, '_MyObject1__x') = True

当使用dir(obj)和dir(obj1)的时候就可以发现,obj中有个x,obj1中只有_MyObject1__x

NightWatch2

#2 Created at ... [Delete] [Delete and Lock User]

有个对象查询写错了,obj少写了1

print('hasattr(obj1, \'x\') =', hasattr(obj1, 'x')) # 有属性'x'吗?

结果是: hasattr(obj1, 'x') = False


  • 1

Reply