[ 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
[ python ] hasattr()、getattr()、setattr() 三者关系及运用的更多相关文章
- Python hasattr,getattr,setattr,delattr
#!/usr/bin/env python # -*- coding:utf-8 -*- # 作者:Presley # 邮箱:1209989516@qq.com # 时间:2018-11-04 # 反 ...
- Python的getattr(),setattr(),delattr(),hasattr()及类内建__getattr__应用
@Python的getattr(),setattr(),delattr(),hasattr() 先转一篇博文,参考.最后再给出一个例子 getattr()函数是Python自省的核心函数,具体使用大体 ...
- 【转】Python的hasattr() getattr() setattr() 函数使用方法详解
Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值 ...
- python 内置函数的补充 isinstance,issubclass, hasattr ,getattr, setattr, delattr,str,del 用法,以及元类
isinstance 是 python中的内置函数 , isinstance()用来判断一个函数是不是一个类型 issubclass 是python 中的内置函数, 用来一个类A是不是另外一个 ...
- hasattr() & getattr() & setattr()
Python的hasattr() getattr() setattr() 函数使用方法详解 感谢作者 ---> 原文链接 hasattr(object, name) 判断一个对象里面是否有n ...
- 反射之hasattr() getattr() setattr() 函数
Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断object中有没有一个name字符串对应的方法或属性,返回B ...
- isinstance/type/issubclass的用法,反射(hasattr,getattr,setattr,delattr)
6.23 自我总结 面向对象的高阶 1.isinstance/type/issubclass 1.type 显示对象的类,但是不会显示他的父类 2.isinstance 会显示的对象的类,也会去找对象 ...
- [转]Python的getattr(),setattr(),delattr(),hasattr()
getattr()函数是Python自省的核心函数,具体使用大体如下: 获取对象引用getattrGetattr用于返回一个对象属性,或者方法 class A: def __init__(self): ...
- python eval() hasattr() getattr() setattr() 函数使用方法详解
eval() 函数 --- 将字符串str当成有效的表达式来求值并返回计算结果. 语法:eval(source[, globals[, locals]]) ---> value 参数: sour ...
随机推荐
- [HZOI2016]偏序&[HZOI2015]偏序II K维偏序问题
description Cogs: [HZOI2016]偏序 [HZOI2015]偏序 II data range \[ n\le 5\times 10^4\] solution 嵌套\(CDQ\)的 ...
- [CF785E]Anton and Permutation
题目大意:有一串数为$1\sim n(n\leqslant2\times10^5)$,$m(m\leqslant5\times10^4)$次询问,每次问交换位置为$l,r$的两个数后数列中逆序对的个数 ...
- BZOJ5288 & 洛谷4436 & LOJ2508:[HNOI/AHOI2018]游戏——题解
https://www.lydsy.com/JudgeOnline/problem.php?id=5288 https://www.luogu.org/problemnew/show/P4436 ht ...
- Mysql数据库的主从复制
怎么安装mysql数据库,这里不说了,只说它的主从复制,步骤如下: 1.主从服务器分别作以下操作: 1.1.版本一致 1.2.初始化表,并在后台启动mysql 1.3.修改root的密码 2.修 ...
- Linux之异步通知20160702
异步通知,主要说的是使用信号的方式,同时使用信号也是实现进程之间通信的一种方式. 多的不说,我们直接看代码: 首先应用程序的: #include <sys/types.h> #includ ...
- ACE反应器(Reactor)模式(2)
转载于:http://www.cnblogs.com/TianFang/archive/2006/12/18/595808.html 在Socket编程中,常见的事件就是"读就绪" ...
- Ultra-QuickSort POJ - 2299 树状数组求逆序对
In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a seque ...
- 再来说一说sudo
app ALL = (ALL:ALL) ALL eric.zhan ALL = (app : app) ALLDefaults:eric.zhan runas_default=app 如 ...
- bzoj 3246 [Ioi2013]Dreaming 贪心
[Ioi2013]Dreaming Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 638 Solved: 241[Submit][Status][Di ...
- ZooKeeper入门(四)
入门:使用ZooKeeper的协调分布式应用 这个文档使你对ZooKeeper快速入门,它主要针对想尝试它的开发者.并且包含简单的单机的ZooKeeper服务的安装说明,一些验证是否运行的命令,和一个 ...