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)
目录
相关文章
|
8月前
|
JSON 数据格式 索引
Python内置函数如`print()`输出信息,`len()`计算长度
【6月更文挑战第23天】Python内置函数如`print()`输出信息,`len()`计算长度,`type()`识别类型,`range()`生成序列,`sum()`求和,`min()`和`max()`找极值,`abs()`取绝对值,`round()`四舍五入,`sorted()`排序,`zip()`和`enumerate()`组合及遍历,`map()`和`filter()`应用函数。标准库如`os`用于操作系统交互,`sys`处理解释器信息,`math`提供数学运算,`re`支持正则表达式,`json`处理JSON数据。学习这些能提升编程效率。
80 5
|
8月前
|
索引 Python
【超全面】Python内置函数详解(三)
【超全面】Python内置函数详解(三)
|
8月前
|
Java 索引 Python
【超全面】Python内置函数详解(一)
【超全面】Python内置函数详解(一)
|
8月前
|
Sentinel Python
【超全面】Python内置函数详解(二)
【超全面】Python内置函数详解(二)
|
8月前
|
索引 Python 安全
【Python内功心法】:深挖内置函数,释放语言潜能
【Python内功心法】:深挖内置函数,释放语言潜能
|
7月前
|
存储 Python
`input()` 函数是 Python 中的一个内置函数,用于从用户那里获取输入。
`input()` 函数是 Python 中的一个内置函数,用于从用户那里获取输入。
|
9月前
|
Python
Python 新版本有75个内置函数,你不会不知道吧(1)
Python 新版本有75个内置函数,你不会不知道吧(1)
Python 新版本有75个内置函数,你不会不知道吧(1)
|
9月前
|
Python 容器
python内置函数、数学模块、随机模块(二)
python内置函数、数学模块、随机模块(二)
|
8月前
|
Python
Python 内置函数
Python 内置函数
|
9月前
|
Python
Python 内置函数
Python 内置函数

热门文章

最新文章