python-getattr/hasattr内置函数
1、getattr() 是python中的一个内置函数,用来获取对象中的属性值
2、getattr(obj,name,default) 其中 obj 为对象名,name 是对象中的属性;必须为字符串;default为默认值,当属性不存在时的返回值
看一下源代码:
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
看一下例子:
class Persion(): # def __init__(self): # self.name = "richard" # self.age = 22 # self.weight = 60 # self.country = 'China' name = "richard" age = 22 weight = 60 country = 'China' if __name__ == '__main__': x = getattr(Persion,'age',10) print(x)
运行打印:
3、 hasattr()函数用于判断对象是否包含对应的属性
hasattr(object,name) -- object--对象,name--字符串,属性 return,如果对象中含有该属性返回true,否则返回false。
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