如何判断对象是否存在某个私有属性

来源:互联网 发布:剑灵烛魔武器属性优化 编辑:程序博客网 时间:2024/04/27 14:26
一般利用Python的内置函数hasattr(object, name)来判断对象object的属性(用name表示)是否存在。如果属性存在,则返回True,否则返回False。如果属性是私有的,则需要特别注意,使用Python直接访问私有属性方式:
实例化对象名._类名__私有属性名
来判断。
#-*- coding: UTF-8 -*-class TestClass(object):    def __init__(self):        self.X = 10        self._Y = 10        self.__Z = 10        def GetX(self):        if hasattr(self, "X"):            print "X: True"        def GetY(self):        if hasattr(self, "_Y"):            print "_y: True"        def GetZ(self):        if hasattr(self, "__Z"):  #私有变量,通过对象无法访问,返回False,实际属性存在            print "__Z: False"        elif hasattr(self, "_TestClass__Z"):            print "__Z: True"if __name__ == '__main__':    print "start main"    test = TestClass()    test.GetX()    test.GetY()    test.GetZ()


2 0
原创粉丝点击