Python introspection and reflection

Introspection#

This is also the sturdy feature of python.

Introspection is the type of object that a program written in an object-oriented language can know at runtime. A simple sentence is the type of object that can be obtained at runtime. Such as type(), dir(), getattr(), hasattr(), isinstance ().

a =[1,2,3]
b ={'a':1,'b':2,'c':3}
c = True
print type(a),type(b),type(c) # <type 'list'><type 'dict'><type 'bool'>
print isinstance(a,list)  # True

reflection#

The reflection mechanism is to dynamically determine the type of an object at runtime, and call object properties, methods, and import modules through strings. It is a string-based event-driven

hasattr

def hasattr(*args,**kwargs): # real signature unknown
"""
Return whether the object has an attribute with the given name.
This is done by calling getattr(obj, name) and catching AttributeError."""
pass

We know from the source code comment that it returns whether the object has an attribute with the specified name. And it is judged by calling getattr and catching AttributeError exception. Just like the attribute call above, we can use hasattr(a, "test") to judge. We can also think through the source code comments. Can eval also implement this method?

def has_attr(obj, name):try:eval("obj.%s()"% name)return True
 except AttributeError as e:return False

a =Base()ifhas_attr(a,"test"):eval("a.test()")

# Output:
Base
test
test

But this method is flawed, because the test output is twice, because we call test() twice, which is not the same as what we want. If you use hasattr, this function will not be called once in the judgment.

getattr()

With a function to determine whether the attribute exists, then there must be a function to get the attribute.

def getattr(object, name,default=None): # known special caseof getattr
"""
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."""
pass

From the source code comments, we can know that the attribute named name of the object object is obtained. If the default parameter is provided with object.name, then the default value will be returned when the attribute does not exist. The same is the above example:

a =Base()ifhasattr(a,"test"):
 func =getattr(a,"test")func()
# Output:
Base
test

From the example, we can see that hasattr did not call the test function, and what getattr obtained was a function object and did not call it. The a.test() function was executed only when we actively executed func(), which is compared to exec and eval are much more flexible.

setattr

Judging and getting properties are there, so setting properties is also needed.

def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.setattr(x,'y', v) is equivalent to ``x.y = v''"""
pass

Recommended Posts

Python introspection and reflection
Python and Go
[python] python2 and python3 under ubuntu
Python deconstruction and packaging
Python3 configuration and entry.md
Python automated operation and maintenance 2
Python introduction and environment installation
Python know crawler and anti crawler
centos7 install python3 and ipython
ubuntu18.04 compile and install python3.8
Centos 6.10 reinstall python and yum
Python open read and write
CentOS7 install python3 and pip3
Python automated operation and maintenance 1
Python data structure and algorithm
Python multi-process and multi-thread basics
CentOS 6.9 compile and install python
What is introspection in python
CentOS 6 compile and install python 3
Generators and iterators in Python
Python file read and write operations
Python and js interactive call method
Magic methods and uses of Python
Python judges positive and negative numbers
python ftp upload files and folders
Python crawler | Cognitive crawler request and response
FM algorithm analysis and Python implementation
Common errors and solutions in python
Python implements string and number splicing
Python function definition and parameter explanation
CentOS quickly install Python3 and pip3
Mongodb and python interaction of python crawler
Install Python3 and ansible under CentOS8
Python processing PDF and CDF examples
Played with stocks and learned Python
Configure python3 environment on centos7 and
Python reads and writes json files
Python implements username and password verification
Install Python3 and Py under CentOS7
Python basic syntax and number types
Python learning os module and usage
Getting Started with Python-4: Classes and Objects
Python restful framework interface development and implementation
Python process and thread summary case analysis
How to use and and or in Python
Python tricks and tricks-continue to be updated...
Python implementation of intersection and IOU tutorial
Getting started with python-2: functions and dictionaries
Naive Bayes algorithm and its Python implementation
Centos python3 compile installation and compile gcc upgrade
Example of python calculating derivative and plotting
Python and scrapy deployment in centos environment
Python implements singly linked lists and dictionaries
Deploy python3 and nginx projects on ubuntu18.04
How does python distinguish return and yield
Python file and directory operation code summary
Talking about Python multithreading and program lock
Python process and thread summary case analysis