hasattr(object, name)函数:
判断一个对象里面是否有name属性或者name方法,返回bool值,有name属性(方法)返回True,否则返回 False。
注意:name 要使用引号括起来。
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
res = hasattr(functiondemo, 'name') #判断对象是否有 name 属性,True
res = hasattr(functiondemo, "run") #判断对象是否有 run 方法,True
res = hasattr(functiondemo, "age") #判断对象是否有 age 属性,False
print(res)
getattr(object, name[,default]) 函数:
获取对象 object 的属性或者方法,如果存在则打印出来,如果不存在,打印默认值,默认值可选。
注意:如果返回的是对象的方法,则打印结果是:方法的内存地址,如果需要运行这个方法,可以在后面添加括号()。
functiondemo = function_demo()
getattr(functiondemo, 'name') #获取 name 属性,存在就打印出来--- demo
getattr(functiondemo, "run") #获取 run 方法,存在打印出 方法的内存地址---<bound method function_demo.run of
<main.function_demo object at 0x10244f320>>
getattr(functiondemo, "age") #获取不存在的属性,报错如下:
Traceback (most recent call last):
File "/Users/liuhuiling/Desktop/MT_code/OpAPIDemo/conf/OPCommUtil.py", line 39, in <module>
res = getattr(functiondemo, "age")
AttributeError: 'function_demo' object has no attribute 'age'
getattr(functiondemo, "age", 18) #获取不存在的属性,返回一个默认值
setattr(object,name,values)函数:
给对象的属性赋值,若属性不存在,先创建再赋值
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
res = hasattr(functiondemo, 'age') # 判断 age 属性是否存在,False
print(res)
setattr(functiondemo, 'age', 18 ) #对 age 属性进行赋值,无返回值
res1 = hasattr(functiondemo, 'age') #再次判断属性是否存在,True
综合使用:
class function_demo(object):
name = 'demo'
def run(self):
return "hello function"
functiondemo = function_demo()
res = hasattr(functiondemo, 'addr') # 先判断是否存在 if res:
addr = getattr(functiondemo, 'addr')
print(addr)else:
addr = getattr(functiondemo, 'addr', setattr(functiondemo, 'addr', '北京首都'))
#addr = getattr(functiondemo, 'addr', '美国纽约')
print(addr)
Python 中如何动态获取和设置对象的属性?
if hasattr(Parent,'x'):
print(getattr(Parent,'x'))
setattr(Parent,'x',3)
print(getattr(Parent,'x'))