Home  >  Article  >  Backend Development  >  What is introspection in Python?

What is introspection in Python?

Guanhui
Guanhuiforward
2020-06-22 13:37:302047browse

What is introspection in Python?

What is introspection?

In daily life, introspection is an act of self-examination.

In computer programming, introspection refers to the ability to examine something to determine what it is, what it knows, and what it can do. Introspection provides programmers with great flexibility and control.

To put it more simply and straightforwardly: introspection means that when a program written in an object-oriented language is running, it can know the type of the object. To put it simply, the type of object can be known at runtime.

For example, python, buby, object-C, and c all have the ability to introspect. Among them, c has the weakest ability to introspect. It can only know what type it is, while python can know what type it is, and also What properties does it have.

The best way to understand introspection is through examples: Type introspection Here are examples of introspection in various programming languages ​​(the examples in this link are very important, maybe it is difficult for you to understand what introspection is through narrative, But through these examples, you can understand it at once)

Back to Python, the more common introspection mechanisms (function usage) in Python are: dir(), type(), hasattr() , isinstance(), through these functions, we can know the type of the object when the program is running, determine whether a certain attribute exists in the object, and access the attributes of the object.

dir()

The dir() function is probably the most famous part of Python’s introspection mechanism. It returns a sorted list of the property names of any object passed to it. If no object is specified, dir() returns the name in the current scope. Let's apply the dir() function to the keyword module and see what it reveals:


>>> import keyword
>>> dir(keyword)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'iskeyword', 'kwlist', 'main']

type()

The type() function helps us determine whether the object is a string, an integer, or another type of object. It does this by returning a type object, which can be compared to the types defined in the types module:


>>> type(42)<class &#39;int&#39;>
>>> type([])<class &#39;list&#39;>

isinstance()

You can use the isinstance() function to test an object to determine whether it is an instance of a specific type or custom class:


>>> isinstance("python", str)
True

help usage expansion in Python introspection:

Open IDLE of python and enter the python interpreter. The python interpreter itself is considered a main module, and then at the interpreter prompt >>> Enter some information we want to know, so first we will ask for help, so enter help, then enter help(), we will enter the help utility, and then follow the prompts keywords, modules, to understand Python keywords and modules that come with Python or are additionally installed and defined by us. If you want to exit, enter 'q' and press Enter.

If we want to know about an object (all objects in python can be considered objects), we can also ask for help(), but we need to enter the name of the object in brackets in the format help(object), for example help(print), since the object has too much introspection content, some only paste part of the content.


>>> help
Type help() for interactive help, or help(object) for help about object.
>>> help()

Welcome to Python 3.6&#39;s help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
...
help> keywords

Here is a list of the Python keywords. Enter any keyword to get more help.

False        def         if         raise
None        del         import       return
True        elif        in         try
and         else        is         while
as         except       lambda       with
assert       finally       nonlocal      yield
break        for         not         
class        from        or         
continue      global       pass        

help> modules

Please wait a moment while I gather a list of all available modules...

PIL         base64       idlelib       runpy
__future__     bdb         idna        runscript
__main__      binascii      idna_ssl      sched
_ast        binhex       imaplib       scrolledlist
_asyncio      bisect       imghdr       search
_bisect       browser       imp         
...
Enter any module name to get more help. Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".
>>> help(&#39;print&#39;)
Help on built-in function print in module builtins:

print(...)
  print(value, ..., sep=&#39; &#39;, end=&#39;\n&#39;, file=sys.stdout, flush=False)
  
  Prints the values to a stream, or to sys.stdout by default.
  Optional keyword arguments:
  file: a file-like object (stream); defaults to the current sys.stdout.
  sep:  string inserted between values, default a space.
  end:  string appended after the last value, default a newline.
  flush: whether to forcibly flush the stream.

Recommended tutorials: "Python Tutorial" "Python Tutorial"

The above is the detailed content of What is introspection in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete