Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Python introspection Mechanism

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail the example analysis of the introspection mechanism of Python. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

What is introspection?

In the field of computer programming, introspection is a kind of ability, which is to know the type and internal structure of the object through a certain mechanism. The introspection ability of Python is still very powerful, because everything in Python is an object, we can obtain not only the type of the object, but also the internal properties of the object. Let's take a look at some of the ways in Python to provide powerful introspection.

Dir () function

It is one of the most important functions for introspection. It returns all the properties and methods owned by an object in the form of a list, and if dir () does not pass any parameters, the default is to find what objects are in the current namespace.

User = {"nickname": "tigeriaf", "level": 2} print (dir (user))

The execution result is:

The above dir () introspects the names of all the methods of a dictionary object. This is very helpful when we can't remember the name of a method for an object.

Type () function and id () function

The type () function returns the type of an object. For example:

Print (type ('tigeriaf')) # result output is print (type (2)) # result output is print (type ([1,2,3])) # result output is

The id () function returns the unique identifier of the object, which is an integer, and in CPython the id () function is used to get the memory address of the object. For example:

Print (id ('tigeriaf'))

# the result output is 51064768

Inspect module

Inspect is the standard library of Python, which provides more powerful introspection capabilities and provides many functions to help get information about objects, such as modules, classes, methods, functions, backtracking, frame objects, and code objects.

The module provides four main functions: type checking, getting source code, checking classes and functions, and checking the call stack of the interpreter. Here are some of the common methods:

Getmembers (object, predicate=None) function

Is based on dir () and returns a (name, value) list of all the members of the object. The content returned is more than the _ _ dict__ of the object. Predicate is an optional parameter, and only members judged by this function to be True are returned.

For example:

Import inspectprint (inspect.getmembers (list))

Signature (obj, *, follow_wrapped=True) function

An object of type inspect.Signature will be returned with a value of all the parameters of this function.

Getmodule (object) function

Returns the module that defines the object.

Getsource (object) function

Returns the source code of the object.

Getsourcelines (object) function

Returns a tuple, the first item of which is a list of the source lines of the object, and the second item is the line number of the first line of source code. For example:

Import inspectdef test (a: int): print (a) print (inspect.signature (test)) print (inspect.getmodule (test)) print (inspect.getsource (test)) print (inspect.getsourcelines (test))

The implementation results are as follows:

Ismodule (), isclass (), ismethod (), isfunction (), isgenerator () functions, etc.

A series of methods to determine the type of object are mostly functions that encapsulate statements such as isinstance (object, types.FunctionType).

If the usual development of modules, classes of the operation is more, then the inspect module must learn.

Hasattr () function and getattr () function

The dir () function returns a list of all the attributes of an object, but if you only want to test the existence of one or more attributes, you need the hasattr () function and the getattr () function to determine whether the object has an attribute and get a property value. For example:

Class MyObj: def _ init__ (self): self.name = 'my_obj' self.a = 1 self.b = [1,2,3] myobj = MyObj () print (getattr (myobj, "name")) print (getattr (myobj, "b")) print (hasattr (myobj, "a") print (hasattr (myobj, "c"))

The execution result is:

This is the end of the article on "sample Analysis of Python introspection Mechanism". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report