[ python ] hasattr()、getattr()、setattr() 三者关系及运用
hasattr(object, name)
判断一个对象(object)是否存在name属性或方法,返回boolean值,有name属性返回True, 否则返回False
In [1]: class Test(object):
   ...:     name = 'hkey'
   ...:     def hello(self):
   ...:         print('hello', self.name)
   ...:
In [2]: t = Test()
In [3]: print(hasattr(t, 'name'))		# 注意:属性'name'是需要引号引起来的
True
In [4]: print(hasattr(t, 'hello'))		# 方法也是类的属性
True
getattr(object, name[, default])
获取对象object的属性或方法(name), 如果存在打印出来,如果不存在,打印默认值,默认值可选,默认值不存在报错对象没有该属性;
In [1]: class Test(object):
   ...:     name = 'hkey'
   ...:     def hello(self):
   ...:         print('hello ', self.name)
   ...:
In [2]: t = Test()
In [3]: print(getattr(t, 'name'))
hkey
In [4]: print(getattr(t, 'hello'))
<bound method Test.hello of <__main__.Test object at 0x000001499524EE80>>
In [5]: print(getattr(t, 'age'))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-bd4a642cfb8c> in <module>()
----> 1 print(getattr(t, 'age')) 	# 没有该属性或方法
AttributeError: 'Test' object has no attribute 'age'
In [6]: print(getattr(t, 'age', 20)) 	# 设置默认值
20
setattr(object, name, values)
给对象的属性赋值,若属性不存在,先创建再赋值
# object不存在属性(age), 用 setattr 新增属性 'age'
In [1]: class Test(object):
   ...:     name = 'hkey'
   ...:     def hello(self):
   ...:         print('hello ', self.name)
   ...:
In [2]: t = Test()
In [3]: print(hasattr(t, 'age'))
False
In [4]: setattr(t, 'age', 20)
In [5]: print(hasattr(t, 'age'))
True
In [6]: print(getattr(t, 'age'))
20
# object 存在属性(name), 用 setattr 覆盖原属性值
In [1]: class Test(object):
   ...:     name = 'hkey'
   ...:     def hello(self):
   ...:         print('hello ', self.name)
   ...:
In [2]: t = Test()
In [3]: print(hasattr(t, 'name')) 	# 使用 hasattr 检查object 是否存在'name'属性, True为存在
True
In [4]: setattr(t, 'name', 'superman') 	# setattr 重新为'name'属性赋值为'superman'
In [5]: print(getattr(t, 'name')) 	# 使用getattr 获取'name'属性的值
superman
In [6]: print(t.name) 	# 直接调用实例't'的name属性
superman
从上面的实例发现,如果object已经存在属性,再次使用setattr为该属性赋值,该属性会发生变化,这里值得注意。
hasattr(), getattr(), setattr() 使用场景
* 作为反射对程序进行解耦操作 *
In [1]: class Test(object):
   ...:     def __init__(self):
   ...:         self.x = 1
   ...:         self.y = 2
   ...:
   ...:     def sum(self):
   ...:         print(self.x + self.y)
   ...:
   ...:     def sub(self):
   ...:         print(self.x - self.y)
   ...:
In [2]: t = Test()
In [3]: while True:
   ...:     cmd = input('-->').strip()
   ...:     if hasattr(t, cmd): 	# 'hasattr' 判断 'cmd' 属性是否存在
   ...:         func = getattr(t, cmd) 	# getattr 获取 'cmd' 属性的值
   ...:         func() 	# 执行该属性
   ...:     else:
   ...:         setattr(t, cmd, t.sum) 	# 如果输入不存在的属性名, 使用 'setattr' 重新为 'cmd' 赋值为 't.sum' 
   ...:         func = getattr(t, cmd)  # getattr 获取 'cmd' 属性的值
   ...:         func() 	# 执行该属性
   ...:
# 执行结果:
-->sum
3
-->sub
-1
-->dddddd
3
 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号