ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python:hasattr() getattr() setattr() 函数

2020-03-21 12:02:16  阅读:253  来源: 互联网

标签:... name setattr Python age getattr self 属性


hasattr(object, name)

判断一个对象里面是否有name属性或者name方法,返回BOOL值,有name特性返回True, 否则返回False。

class test():
     name="xiaohua"
     def run(self):
         return "HelloWord"

>>> t=test()
>>> hasattr(t, "name") #判断对象有name属性
True
>>> hasattr(t, "run")  #判断对象有run方法
True

getattr(object, name[,default])

获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选。需要注意的是,如果是返回的对象的方法,返回的是方法的内存地址,如果需要运行这个方法,可以在后面添加一对括号。

getattr(obj,name[,default]) 其中obj为对象名,name是对象中的属性,必须为字符串

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> getattr(t, "name") #获取name属性,存在就打印出来。
'xiaohua'
>>> getattr(t, "run")  #获取run方法,存在就打印出方法的内存地址。
<bound method test.run of <__main__.test instance at 0x0269C878>>
>>> getattr(t, "run")()  #获取run方法,后面加括号可以将这个方法运行。
'HelloWord'
>>> getattr(t, "age")  #获取一个不存在的属性。
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age","18")  #若属性不存在,返回一个默认值。
'18'
>>>

setattr(object, name, values)

给对象的属性赋值,若属性不存在,先创建再赋值。

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> hasattr(t, "age")   #判断属性是否存在
False
>>> setattr(t, "age", "18")   #为属相赋值,并没有返回值
>>> hasattr(t, "age")    #属性存在了
True
>>>

综合的用法

判断一个对象的属性是否存在,若不存在就添加该属性。

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> getattr(t, "age")    #age属性不存在
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age", setattr(t, "age", "18")) #age属性不存在时,设置该属性
'18'
>>> getattr(t, "age")  #可检测设置成功
'18'
>>>

针对类的字典式使用

class Student:
    def __init__(self,name,identity,age):
        self._name = name
        self._identity = identity
        self.age = age
    def __getitem__(self,item):
        if isinstance(item,str):
            return getattr(self,"_" + item)

>>> st=Student("Huang Lei",1323010212,12)
>>> st["age"]
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    st["age"]
  File "<pyshell#54>", line 8, in __getitem__
    return getattr(self,"_" + item)
AttributeError: 'Student' object has no attribute '_age'


>>> st["name"]
'Huang Lei'
>>> s=["Huang Lei",1323010212,12]

参考其他文章:
https://www.cnblogs.com/cenyu/p/5713686.html
https://blog.csdn.net/AugustMoore/article/details/80989128

标签:...,name,setattr,Python,age,getattr,self,属性
来源: https://www.cnblogs.com/g2thend/p/12538361.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有