hasattr(object, name)
判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。
举个例子:
class test(): ... name="xiaocai" ... def hello(self): ... return "HelloWord" ... >>> t=test() >>> hasattr(t, "name") #判断对象有name属性 True >>> hasattr(t, "hello") #判断对象有hello方法 True
或者:
class variable: x = 1 y = 'a' z = True dd = variable() print(hasattr(dd, 'x')) print(hasattr(dd, 'y')) print(hasattr(dd, 'z')) print(hasattr(dd, 'no')) True True True False