Python内置函数--getattr&setattr&delattr&hasattr

简介: Python内置函数--getattr&setattr&delattr&hasattr

getattr

此函数将对象和属性的名称作为参数。它返回该对象中存在的属性的值。

def getattr(object, name, default=None): # known special case of getattr
    """
    getattr(object, name[, default]) -> value
    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.
    """
    pass

源码中介绍到,getattr(x,'y')的写法等价于x.y。那么我们证实一下:

class Attr:
    name = "清安"
res = getattr(Attr,'name')
print(res)
attr = Attr.name
print(attr)
"""
清安
清安
"""

💥getattr还有个默认值default:

class Attr:
    name = "清安"
res = getattr(Attr,'QA','找不到这个名字')
print(res)
"""找不到这个名字"""

也就是说,你调用某个属性,而属性不存在,就可以用这个默认值,直观的告诉自己,异常信息。


💥getattr还可以进行传值

class Attr:
    name = "清安"
    def information(self, age: int):
        return f"{self.name}今年{age}岁了"
res = getattr(Attr(),'information','找不到这个名字')(60)
print(res)
"""清安今年60岁了"""

setattr

def setattr(x, y, v): # real signature unknown; restored from __doc__
    """
    Sets the named attribute on the given object to the specified value.
    setattr(x, 'y', v) is equivalent to ``x.y = v''
    """
    pass

上述介绍到setattr(x,'y',v)等价于x.y=v,证实一下:

class Attr:
    name = "清安"
    def information(self, age):
        return f"{self.name}今年{age}岁了"
setattr(Attr,"name",'拾贰')
print(Attr.name)
set = Attr.name = "拾贰长大了"
print(set)
"""
拾贰
拾贰长大了
"""

delattr

def delattr(x, y): # real signature unknown; restored from __doc__
    """
    Deletes the named attribute from the given object.
    delattr(x, 'y') is equivalent to ``del x.y''
    """
    pass

老样子,delattr(x,'y')等价于del x.y

class Attr:
    name = "清安"
    def infomation(self,age):
        return f"{self.name}今年{age}岁了!"
res = delattr(Attr,'name')
print(res)
attr = Attr().infomation(18)
print(attr)
"""
None
AttributeError: 'Attr' object has no attribute 'name'
"""

删除了也就没有了,所以就没这个属性了

hasattr

def hasattr(*args, **kwargs): # real signature unknown
    """
    Return whether the object has an attribute with the given name.
    This is done by calling getattr(obj, name) and catching AttributeError.
    """
    pass

返回对象是否具有具有给定名称的属性。也就是True,False。

class Attr:
    name = "清安"
    def infomation(self,age):
        return f"{self.name}今年{age}岁了!"
res = hasattr(Attr,'name')
print(res)
"""True"""

💥简单运用

class Attr:
    name = "清安"
    def infomation(self,age):
        return f"{self.name}今年{age}岁了!"
if hasattr(Attr,'name'):
    res = getattr(Attr,"name")
    print(res)
目录
相关文章
|
2天前
|
程序员 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,它可以简洁地实现函数的增强、扩展和重用。本文将深入探讨Python中装饰器的工作原理、常见应用场景以及如何自定义装饰器,帮助读者更好地理解和运用这一重要的编程概念。
|
3天前
|
数据采集 Python
10个Python set 常用操作函数!,bilibili面试题
10个Python set 常用操作函数!,bilibili面试题
10个Python set 常用操作函数!,bilibili面试题
|
3天前
|
数据采集 数据挖掘 Python
Python学习——函数,2024年最新手持4个大厂offer的我
Python学习——函数,2024年最新手持4个大厂offer的我
|
3天前
|
数据采集 数据挖掘 关系型数据库
Excel计算函数(计算机二级)(1),2024年最新2024Python架构面试指南
Excel计算函数(计算机二级)(1),2024年最新2024Python架构面试指南
|
3天前
|
存储 Java Shell
【Python学习教程】Python函数和lambda表达式_6(1),2024蚂蚁金服面试题及答案
【Python学习教程】Python函数和lambda表达式_6(1),2024蚂蚁金服面试题及答案
|
3天前
|
Python
Python基础教程: math库常用函数(1),Python这些高端技术只有你还不知道
Python基础教程: math库常用函数(1),Python这些高端技术只有你还不知道
|
4天前
|
机器学习/深度学习 数据采集 自然语言处理
python函数参数的传递、带星号参数的传递,2024年大厂Python高级面试题分享
python函数参数的传递、带星号参数的传递,2024年大厂Python高级面试题分享
|
4天前
|
Python
Python 使用type()函数
【5月更文挑战第10天】
13 4
|
4天前
|
Python
Python使用isinstance()函数
【5月更文挑战第10天】Python使用isinstance()函数
9 2
|
4天前
|
缓存 Python
Python中的装饰器:优雅而强大的函数装饰技术
在Python编程中,装饰器是一种强大而灵活的技术,它可以使函数具有额外的功能,而不需要改变函数的核心代码。本文将深入探讨装饰器的原理、用法以及实际应用场景,帮助读者更好地理解和利用这一重要的Python编程工具。