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)
目录
相关文章
|
4月前
|
存储 JavaScript Java
(Python基础)新时代语言!一起学习Python吧!(四):dict字典和set类型;切片类型、列表生成式;map和reduce迭代器;filter过滤函数、sorted排序函数;lambda函数
dict字典 Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 我们可以通过声明JS对象一样的方式声明dict
307 2
|
4月前
|
算法 Java Docker
(Python基础)新时代语言!一起学习Python吧!(三):IF条件判断和match匹配;Python中的循环:for...in、while循环;循环操作关键字;Python函数使用方法
IF 条件判断 使用if语句,对条件进行判断 true则执行代码块缩进语句 false则不执行代码块缩进语句,如果有else 或 elif 则进入相应的规则中执行
416 1
|
4月前
|
Java 数据处理 索引
(numpy)Python做数据处理必备框架!(二):ndarray切片的使用与运算;常见的ndarray函数:平方根、正余弦、自然对数、指数、幂等运算;统计函数:方差、均值、极差;比较函数...
ndarray切片 索引从0开始 索引/切片类型 描述/用法 基本索引 通过整数索引直接访问元素。 行/列切片 使用冒号:切片语法选择行或列的子集 连续切片 从起始索引到结束索引按步长切片 使用slice函数 通过slice(start,stop,strp)定义切片规则 布尔索引 通过布尔条件筛选满足条件的元素。支持逻辑运算符 &、|。
269 0
|
5月前
|
设计模式 缓存 监控
Python装饰器:优雅增强函数功能
Python装饰器:优雅增强函数功能
303 101
|
5月前
|
缓存 测试技术 Python
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
249 99
|
5月前
|
存储 缓存 测试技术
Python装饰器:优雅地增强函数功能
Python装饰器:优雅地增强函数功能
230 98
|
5月前
|
缓存 Python
Python中的装饰器:优雅地增强函数功能
Python中的装饰器:优雅地增强函数功能
|
6月前
|
Python
Python 函数定义
Python 函数定义
666 155
|
5月前
|
算法 安全 数据安全/隐私保护
Python随机数函数全解析:5个核心工具的实战指南
Python的random模块不仅包含基础的随机数生成函数,还提供了如randint()、choice()、shuffle()和sample()等实用工具,适用于游戏开发、密码学、统计模拟等多个领域。本文深入解析这些函数的用法、底层原理及最佳实践,帮助开发者高效利用随机数,提升代码质量与安全性。
977 0
|
6月前
|
数据挖掘 数据处理 C++
Python Lambda:从入门到实战的轻量级函数指南
本文通过10个典型场景,详解Python中Lambda匿名函数的用法。Lambda适用于数据处理、排序、条件筛选、事件绑定等简洁逻辑,能提升代码简洁性和开发效率。同时提醒避免在复杂逻辑中过度使用。掌握Lambda,助你写出更高效的Python代码。
358 0

推荐镜像

更多