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

Время опроса


Давайте подведем итог, собрав вместе некоторые из интроспективных технологий, которые мы рассмотрели в последнем разделе. Для этого определим нашу собственную функцию interrogate(), которая выводит различную информацию о любом объекте, передаваемом в нее. Ниже приведен код, который сопровождается несколькими примерами его применения:



Листинг 35. Никто и не надеялся

>>> def interrogate(item): ... """Print useful information about item.""" ... if hasattr(item, '__name__'): ... print "NAME: ", item.__name__ ... if hasattr(item, '__class__'): ... print "CLASS: ", item.__class__.__name__ ... print "ID: ", id(item) ... print "TYPE: ", type(item) ... print "VALUE: ", repr(item) ... print "CALLABLE:", ... if callable(item): ... print "Yes" ... else: ... print "No" ... if hasattr(item, '__doc__'): ... doc = getattr(item, '__doc__') ... doc = doc.strip() # Remove leading/trailing whitespace. ... firstline = doc.split('\n')[0] ... print "DOC: ", firstline ... >>> interrogate('a string') # Строка CLASS: str ID: 141462040 TYPE: <type 'str'> VALUE: 'a string' CALLABLE: No DOC: str(object) -> string >>> interrogate(42) # Целое CLASS: int ID: 135447416 TYPE: <type 'int'> VALUE: 42 CALLABLE: No DOC: int(x[, base]) -> integer >>> interrogate(interrogate) # Функция, определенная пользователем NAME: interrogate CLASS: function ID: 141444892 TYPE: <type 'function'> VALUE: <function interrogate at 0x86e471c> CALLABLE: Yes DOC: Print useful information about item.

Как следует из последнего примера, наша функция interrogate() работает даже сама с собой. Большей ретроспективности вы вряд ли сможете получить.



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