您的位置:首页 > 其它

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

2016-09-12 15:59 288 查看
一般利用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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: