一般利用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()