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)