Because you can use a dynamic variable too:
somevar = 'foo'
getattr(x, somevar)
You can't do that with regular attribute access syntax.
Note that getattr()
also takes an optional default value, to be returned if the attribute is missing:
>>> x = object()
>>> getattr(x, 'foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
>>> getattr(x, 'foo', 42)
42
Using getattr()
you can pull the attribute name from something else, not a literal:
for attrname in dir(x):
print('x.{} = {!r}'.format(attrname, getattr(x, attrname))
or you can use setattr()
to set dynamic attributes:
for i, value in enumerate(dynamic_values):
setattr(i, 'attribute{}'.format(i), value)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…