Python Glossary Русский

all Python 3operatorfunction

operator.attrgetter

calls and access

A factory returning a callable that fetches attributes by fixed name.

Syntax

f = operator.attrgetter('attr')

It understands dotted paths: attrgetter('owner.name') walks the chain of attributes. As with itemgetter, several names yield a tuple: attrgetter('last', 'first') is a handy two-field sort key. A missing attribute raises AttributeError — there is no default value as with getattr.

Examples

import operator
g = operator.attrgetter('real')
print(g(3 + 4j))   # → 3.0
print(operator.attrgetter('real')(3 + 4j) == (3 + 4j).real)   # → True
print(operator.attrgetter('real', 'imag')(3 + 4j))   # → (3.0, 4.0)
print(operator.attrgetter('imag.real')(3 + 4j))   # → 4.0
print(sorted([3 + 9j, 1 + 2j], key=operator.attrgetter('imag')))   # → [(1+2j), (3+9j)]

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy