hasattr()
hasattr(object, name)
#object -- 对象
#name -- 字符串,属性名
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no')) # 没有该属性
True
True
True
False
getattr()
getattr() 函数用于返回一个对象属性值。
getattr(object, name[, default])
object -- 对象。
name -- 字符串,对象属性。
default -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # 获取属性 bar 值
1
>>> getattr(a, 'bar2') # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3) # 属性 bar2 不存在,但设置了默认值
3
>>>
setattr()
setattr() 函数对应函数 getattr(),用于设置属性值,该属性必须存在。
object -- 对象。
name -- 字符串,对象属性。
value -- 属性值。
setattr(object, name, value)
>>>class A(object):
... bar = 1
...
>>> a = A()
>>> getattr(a, 'bar') # 获取属性 bar 值
1
>>> setattr(a, 'bar', 5) # 设置属性 bar 值
>>> a.bar
5
locals()
locals() 函数会以字典类型返回当前位置的全部局部变量。
对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例, 它都返回 True。
locals()
>>>def runoob(arg): # 两个局部变量:arg、z
... z = 1
... print (locals())
...
>>> runoob(4)
{'z': 1, 'arg': 4} # 返回一个名字/值对的字典
>>>