Python之hasattr,getattr与setattr的使用
2021/6/13 20:21:21
本文主要是介绍Python之hasattr,getattr与setattr的使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
一. 定义一个类
class Person(object): def __init__(self, name): self.name = name def fun1(self): print('fun1')
二. hasattr
检查某对象
Object
中是否包某个属性或方法。语法为:hasattr(object,name)
。
(一). 用法
person = Person('test') print(hasattr(person, 'name')) # True print(hasattr(person, 'name1')) # False print(hasattr(person, 'fun1')) # True
由于name1
在Person
这个类中不存在会返回False
,而name
存在就会返回True
. 可以使用hasattr
来判断某对象中是否存在某个属性或者某个方法。
三. getattr
获取某个对象
Object
中的属性的属性值。语法为:getattr(object,name,default=None)
。
(一). 用法
person1 = Person('test1') print(getattr(person1, 'name')) # test1 print(getattr(person1, 'name1', '没有值')) # 没有值 # 不建议使用getattr操作获取函数的返回值。 # <bound method Person.fun1 of <__main__.Person object at 0x7fa7aa29b460>> print(getattr(person1, 'fun1'))
注意:如果使用getattr
来获取不存在的属性时会出现报错。个人建议先使用hasattr
判断你需要的属性存在时再使用getattr
来获取值。
四. setattr
给某个对象
Object
添加一个属性或方法设置其属性或方法的值。语法为:setattr(object,name,value)
。
(一). 用法
1. 设置属性
person2 = Person('test2') setattr(person2, 'age', 18) print(person2.age) # 18 print(person2.name) # test2 setattr(person2, 'name', 'new test2') print(person2.name) # new test2
2. 设置方法
# 设置不存在的方法。 person3 = Person('test3') def test(): return "test 函数" setattr(person3, 'test', test) print(person3.test()) # test 函数 # 设置同名的方法,同名方法里的内容会随之替换的。 def fun1(): return 'fun1 函数' setattr(person3, 'fun1', fun1) print(person3.fun1()) # fun1 函数
这篇关于Python之hasattr,getattr与setattr的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python