一、hasattr(object, name)
判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。
class MethodTest():
name = "hasattr_test"
def run_func(self):
return "HelloWord"
t = MethodTest()
print hasattr(t, "name")
print hasattr(t, "run_func")
print hasattr(t, "run")
二、getattr(object, name[, default])
获取object对象的属性的值,如果存在则返回属性值,如果不存在分为两种情况:
1)没有default参数时,会直接报错;
2)给定了default参数,若对象本身没有name属性,则会返回给定的default值;
如果给定的属性name是对象的方法,则返回的是函数对象,需要调用函数对象来获得函数的返回值;调用的话就是函数对象后面加括号,如func之于func();
class MethodTest():
name = "hasattr_test"
def run_func(self):
return "HelloWord"
t = MethodTest()
print getattr(t, "name")
print getattr(t, "age")
Traceback (most recent call lxxx
File "xxx.py", line 61, in <module>
print getattr(t, "age")
AttributeError: MethodTest instance has no attribute 'age'
print getattr(t, "age", 30)
print getattr(t, "run_func")
<bound method MethodTest.run_func of <__main__.MethodTest instance at 0x10c8c1550>>
print getattr(t, "run_func")()
三、setattr(object, name, value)
给object对象的name属性赋值value,如果对象原本存在给定的属性name,则setattr会更改属性的值为给定的value;如果对象原本不存在属性name,setattr会在对象中创建属性,并赋值为给定的value
class MethodTest():
name = "hasattr_test"
def run_func(self):
return "HelloWord"
t = MethodTest()
print setattr(t, "name", "setattr_test")
print getattr(t, "name")
print setattr(t, "age", 40)
print getattr(t, "age")
四、参考文档:
1、https://www.cnblogs.com/liangmingshen/p/11361947.html
|