访问我的博客 http://blog.colinspace.com
摘要
Python 对应属性和方法的判断 hasattr/getattr/setattr
hasattr
判断一个对象里面是否有name属性或者方法,返回值为Boolean值, 有name 返回true,反之false
其等同于getattr(object, name)
hasattr(object, name)
getattr
类似于hasattr(object, name)
,但是getattr当name不存在于object的时候返回default值。否则返回实际的值
getattr(object, name[, default])
setattr
给对象的属性复制,如果属性不存在,则先创建再赋值
setattr(object, name, value)
examples
root@pts/1 $ python
Python 3.5.3 (default, Jul 20 2017, 16:49:29)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help(getattr)
>>>
## 定义测试类
>>> class TestAttr():
... name = 'James'
...
... def sayHello(self):
... return 'Hello James'
...
>>> ta = TestAttr()
## ta为object对象类型
>>> ta
<__main__.TestAttr object at 0x7f52d55df5f8>
## hasattr 测试, name属性必须加引号
>>> hasattr(ta, name)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'name' is not defined
>>> hasattr(ta, "name")
True
>>> hasattr(ta, "sayHello")
True
## hasattr 不能像getattr 那样调用函数
>>> hasattr(ta, "sayHello")()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not callable
>>>
## setattr测试,当不存在属性的时候可以创建属性
>>> hasattr(ta, "age")
False
>>> setattr(ta, "age", 28)
>>> hasattr(ta, "age")
True
>>>
## getattr 测试
>>> getattr(ta, "name")
'James'
## 是函数的时候,可以调用函数
>>> getattr(ta, "sayHello")
<bound method TestAttr.sayHello of <__main__.TestAttr object at 0x7f52d55df5f8>>
>>> getattr(ta, "sayHello")()
'Hello James'
>>> getattr(ta, "age")
28
## 不存在的时候得到默认值
>>> getattr(ta, "age2", 18)
18
>>>
Note & Refer to:
从上面的例子中我们看到
- name 参数必须是加引号,不然报错
- name 为函数的时候,调用
getattr(object, name)()
相当于 object.name 调用该name函数
例子用法参考官网地址:
网友评论