Python标准库:内置函数hasattr() getattr() setattr() 函数使用方法详解

hasattr(object, name)

本函数是用来判断对象object的属性(name表示)是否存在。如果属性(name表示)存在,则返回True,否则返回False。参数object是一个对象,参数name是一个属性的字符串表示。

 1 #coding:UTF8
 2 
 3 class Foo():  
 4     def __init__(self):  
 5         self.x = 123  
 6     def test(x):
 7         self.x = x  
 8   
 9 foo = Foo()  
10 print(hasattr(foo, 'x'))   #判断对象有x属性
11 print(hasattr(foo, 'y'))  
12 print(hasattr(foo, 'test'))

输出结果:

1 True
2 False
3 True

getattr(object, name[,default])

获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,可以在后面添加一对括号。

 1 #coding:UTF8
 2 
 3 class Foo():
 4     name = 'Tom'
 5     def run(self):
 6         return 'hello world'
 7     
 8 f = Foo()
 9 print getattr(f,'name')  #获取name属性,存在就打印出来。
10 print getattr(f, 'run') #获取run方法,存在就打印出方法的内存地址。
11 print getattr(f,'run')() #获取run方法,后面加括号可以将这个方法运行。
12 #print getattr(f,'age')  #获取一个不存在的属性。
13 print getattr(f, "age","18")  #若属性不存在,返回一个默认值。

输出结果:

1 Tom
2 <bound method Foo.run of <__main__.Foo instance at 0x0000000002658B08>>
3 hello world
4 18

setattr(object, name, values)

给对象的属性赋值,若属性不存在,先创建再赋值。

 1 #coding:UTF8
 2 
 3 class Foo():
 4     name = 'Tom'
 5     def run(self):
 6         return 'hello world'
 7     
 8 f = Foo()
 9 
10 print hasattr(f,'age')   #判断属性是否存在
11 setattr(f, "age","18")  #若属性不存在,返回一个默认值。
12 print hasattr(f,'age')   #判断属性是否存在
1 False
2 True
View Code
原文地址:https://www.cnblogs.com/qianyuliang/p/6781806.html