Введение в язык Питон
773123a3

Атрибуты


Мы видели, что объекты имеют атрибуты, а функция dir() возвращает список этих атрибутов. Иногда, однако, мы просто хотим определить наличие одного или более атрибутов. И если у объекта есть интересующий нас атрибут, мы часто хотим извлечь этот атрибут. Эти задачи решаются с помощью функций hasattr() и getattr(), как показано в следующем примере:



Листинг 31. Наличие атрибута; получение атрибута

>>> print hasattr.__doc__ hasattr(object, name) -> Boolean

Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.)

>>> print getattr.__doc__ 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.

>>> hasattr(id, '__doc__') 1 >>> print getattr(id, '__doc__') id(object) -> integer

Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.)



Содержание раздела