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() 三者关系及运用的更多相关文章

  1. Python hasattr,getattr,setattr,delattr

    #!/usr/bin/env python # -*- coding:utf-8 -*- # 作者:Presley # 邮箱:1209989516@qq.com # 时间:2018-11-04 # 反 ...

  2. Python的getattr(),setattr(),delattr(),hasattr()及类内建__getattr__应用

    @Python的getattr(),setattr(),delattr(),hasattr() 先转一篇博文,参考.最后再给出一个例子 getattr()函数是Python自省的核心函数,具体使用大体 ...

  3. 【转】Python的hasattr() getattr() setattr() 函数使用方法详解

    Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断一个对象里面是否有name属性或者name方法,返回BOOL值 ...

  4. python 内置函数的补充 isinstance,issubclass, hasattr ,getattr, setattr, delattr,str,del 用法,以及元类

    isinstance   是 python中的内置函数 , isinstance()用来判断一个函数是不是一个类型 issubclass  是python 中的内置函数,  用来一个类A是不是另外一个 ...

  5. hasattr() & getattr() & setattr()

    Python的hasattr() getattr() setattr() 函数使用方法详解   感谢作者 ---> 原文链接 hasattr(object, name) 判断一个对象里面是否有n ...

  6. 反射之hasattr() getattr() setattr() 函数

    Python的hasattr() getattr() setattr() 函数使用方法详解 hasattr(object, name)判断object中有没有一个name字符串对应的方法或属性,返回B ...

  7. isinstance/type/issubclass的用法,反射(hasattr,getattr,setattr,delattr)

    6.23 自我总结 面向对象的高阶 1.isinstance/type/issubclass 1.type 显示对象的类,但是不会显示他的父类 2.isinstance 会显示的对象的类,也会去找对象 ...

  8. [转]Python的getattr(),setattr(),delattr(),hasattr()

    getattr()函数是Python自省的核心函数,具体使用大体如下: 获取对象引用getattrGetattr用于返回一个对象属性,或者方法 class A: def __init__(self): ...

  9. python eval() hasattr() getattr() setattr() 函数使用方法详解

    eval() 函数 --- 将字符串str当成有效的表达式来求值并返回计算结果. 语法:eval(source[, globals[, locals]]) ---> value 参数: sour ...

随机推荐

  1. BZOJ3456:城市规划——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=3456 求出n个点的简单(无重边无自环)无向连通图数目 模数很熟悉,先敲一个NTT. 然后通过推导式 ...

  2. HDU4825:Xor Sum——题解

    http://acm.hdu.edu.cn/showproblem.php?pid=4825 Zeus 和 Prometheus 做了一个游戏,Prometheus 给 Zeus 一个集合,集合中包含 ...

  3. [Leetcode] powx n x的n次方

    Implement pow(x, n). 题意:计算x的次方 思路:这题的思路和sqrt的类似,向二分靠近.例如求4^5,我们可以这样求:res=4.4*4^4.就是将每次在res的基础上乘以x本身, ...

  4. [转载]系统管理:update-alternatives

    http://blog.csdn.net/dbigbear/article/details/4398961 好吧,其实博主也是转载的. update-alternatives --display | ...

  5. python练习:抓取统计log内ip数量

    #!/usr/bin/python #-*- coding: utf- -*- import os import re rawfile = '/var/log/auth.log' def rawpar ...

  6. 使用Android Studio调试UiAutomator过程中遇到的问题

    声明: 这里纪录了个人学习和使用Android Studio调试UiAutomator过程中遇到遇到的问题,不定时进行更新,欢迎一起交流学习 1.Excution faild for task ‘:a ...

  7. oracle重新编译失效对像

    重新编译失效对像可执行utlrp.sql文件: SQL> @?/rdbms/admin/utlrp.sql TIMESTAMP --------------------------------- ...

  8. ARM汇编程序闪烁灯与其反汇编代码比较

    /* *LED闪烁 *led.s */ #define GPJ0CON 0xE0200240 #define GPJ0DAT 0xE0200244 .global _start //把 _start ...

  9. a标签nest问题,即a标签里面嵌套a标签

    方法一:使用div模拟a,监听click事件 方法二:使用<object>标签包裹内部a标签 <div style="width: 200px;height: 200px; ...

  10. [USACO13FEB]出租车Taxi

    洛谷题目链接:[USACO13FEB]出租车Taxi 题目描述 Bessie is running a taxi service for the other cows on the farm. The ...