python reflective introspection

DAY 5. python introspection

This is a long time to write before, when the concept of self-examination and reflection did not understand, after learning Java a little more understanding, self-examination is the ability to get the object of reflection is the ability to manipulate objects, python use getattr()and setattr()implement reflection, while others is introspection, the following content is to mix the two together to say, but do not want to change the contents of Rory it repetitious, the final summary of the aforementioned

method effect
help() Viewing Function module uses detailed description
to you() Return all the properties of the object
type() View Object Types
Hsattr () Check whether the object has a particular property
getattr() To give the object specific properties
setattr() Set specific properties of an object
isinstance() Determining whether an object is a type known
issubclass() Analyzing class is not a subclass of another class of
id() Return address value
callable() Determine whether the object can call

In computing, type introspection is the ability of a program to examine the type or properties of an object at runtime. Some programming languages possess this capability.
In computer science, introspection refers to a computer program at run time (Run time) inspection object (Object) type ability, also generally referred to as a run-time type checking

This is the Wikipedia explanation of introspection (introspection), popular speaking, is introspection in the program is running, is running an ability to know the type of object, most languages ​​have this ability (have a way in type known objects), such as c ++, Java, etc.

Of course, self-reflection and not just for the type of object, such as python introspection can know the object's properties, there are some other understanding

In everyday life, introspection (introspection) is a kind of self-examination behavior.

In computer programming, introspection refers to this ability: Some things to check to determine what it is, what it knows and what it can do. Introspection provides great flexibility and control to the programmer.

Type of introspection is the object-oriented programming language written at runtime, to know the object: that's a little more straightforward. Is a simple, run-time type of the object can be known.

For example c ++ introspection (from Wikipedia)

C ++ type information (RTTI) typeid and dynamic_cast keyword support for run-time type introspection through. dynamic_cast expressions may be used to determine whether a particular object belongs to a particular derived class. E.g:

Person* p = dynamic_cast<Person *>(obj);
if (p != nullptr) {
  p->walk();
}

typeid std :: type_info operator to retrieve the object, a derived type of the object description of the object:

if (typeid(Person) == typeid(*obj)) {
  serialize_person( obj );
}

php introspection (from Wikipedia)

In php, instanceof operator can use a PHP variable determines whether a particular instance of the class

if ($obj instanceof Person) {
    // Do whatever you want
}

Java introspection (from Wikipedia)

The simplest example is the Java introspection type instanceof operator. instanceof operator to determine the specific object belongs to a specific class (or subclass of this class, or the class that implements the interface). E.g:

if (obj instanceof Person) {
    Person p = (Person)obj;
    p.walk();
}

5.1 python way to achieve self-examination

There are many ways to achieve self-reflection python, commonly used help (), dir (), type (), hasattr (), getattr (), setattr (), isinstance (), issubclass (), id (), callable ()

5.1.1 help()

help () function is a function for viewing or use of the module in detail. Predominantly at IDE environment is, has a function to accept any object or method, prints out the documentation of all the functions and string

As you can print documents directly help os module

import os
help(os)
# Help on module os:
#
# NAME
#     os - OS routines for NT or Posix depending on what system we're on.
#
# DESCRIPTION
# 后面的省略了

We can also custom class, function, or module

class Demo:
    """
    this is a Demo
    """
    classVar = 0

    def __init__(self):
        self.var1 = 1

    def output(self):
        print(self.var1)

if __name__ == '__main__':
    help(Demo)

After running will print out complete information about this class

Help on class Demo in module __main__:

class Demo(builtins.object)
 |  this is a Demo
 |  
 |  Methods defined here:
 |  
 |  __init__(self)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  output(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  classVar = 0

Examples of the object will print out information such

Help function will print out a document, the document will not print none

 def demoMethods(a):
        """
        这是一个示例函数
        :param a: 示例形参
        :return: None
        """
        print(a)
    help(demoMethods)
# Help on function demoMethods in module __main__:

# demoMethods(a)
#     这是一个示例函数
#     :param a: 示例形参
#     :return: None

A more detailed look at this article

Python- introspection mechanism

5.1.2 dir ()

dir () is a function of no arguments, return variable in the current scope, and method of the type defined in the list; when arguments, and returns the parameter attributes, list of methods. If the parameter includes a method __dir __ (), which will be called. If the parameter does not contain __dir __ (), which will maximize the collection of parameter information.

dir()
['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'sys']
dir([])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

5.1.3 hasattr(),getattr(),setattr()

class Demo:
    def __init__(self):
        self.var1 = 0
        self.var2 = 1

if __name__ == '__main__':
    demo = Demo()
    if hasattr(demo,'var1'):
        setattr(demo,'var1',2)
    print(getattr(demo,'var1','not find'))  # 2
    print(getattr(demo,'var11','not find'))  # not find
  • Hsattr ()
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.
    这是通过调用getattr(obj,name)并捕获AttributeError来完成的.
    """
    pass
  • setattr()
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''
    setattr(x,‘y’,v)等价于“x.y=v”
    """
    pass
  • getattr()
def getattr(object, name, default=None): # known special case of 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.
    从对象中获取指定名称的属性;getattr(x,‘y’)等同于X.Y。
    如果给定了默认参数,则未找到该属性时将返回该参数。
    如果未指定,则会引发异常。
    """
    pass

5.1.4 isinstance(),issubclass()

>>> help(isinstance)
Help on built-in function isinstance in module builtins:

isinstance(obj, class_or_tuple, /)
    Return whether an object is an instance of a class or of a subclass thereof.
    返回对象是类的实例还是其子类的实例。
    A tuple, as in ``isinstance(x, (A, B, ...))``, may be given as the target to
    check against. This is equivalent to ``isinstance(x, A) or isinstance(x, B)
    or ...`` etc.

instance similar to the type (), just type () does not think that is a subclass of parent class type, without regard to inheritance. isinstance () will be considered sub-class is a parent class type, consider inheritance.

>>> class A:
	pass

>>> a = A()
>>> isinstance(a,type)
False
>>> class B(A):
	pass

>>> b=B()
>>> isinstance(b,A)
True
>>> isinstance(int,type)
True
>>> isinstance(A,type)
True
>>> isinstance(b,type)
False
>>> isinstance(True,int)
True

It can be seen class is a subtype of type, but also verified the yuan class the day before yesterday, and Boolean is a subclass of int

And issubclass () is used to determine a class is a subclass of another class not, two parameters are passed in the name of the class

>>> issubclass(B,A)
True

5.1.5 id()和callable()

  • id (): used to get the memory address of an object
  • callable (): determine whether the object can be called.

5.1.6 type()

This function is written in a metaclass, a type parameter when an incoming object return, which is more commonly used python method introspection

5.2 summary

  • What is introspection

Is simply the program is running to know the type of object (as well as attributes, etc.) the ability to

  • Python method to achieve self-examination
method effect
help() Viewing Function module uses detailed description
to you() Return all the properties of the object
type() View Object Types
Hsattr () Check whether the object has a particular property
getattr() To give the object specific properties
seetattr () Set specific properties of an object
isinstance() Determining whether an object is a type known
issubclass() Analyzing class is not a subclass of another class of
id() Return address value
callable() Determine whether the object can call

Reference article

python face questions

wikipedia Type introspection

Python introspection (reflection) guidelines [turn]

He said in this article

In the author, that is my concept, introspection and reflection is one thing, of course, in fact, I am not very sure and make sure ...

But I saw this sentence Wikipedia

Introspection should not be confused with reflection, which goes a step further and is the ability for a program to manipulate the values, meta-data, properties and/or functions of an object at runtime.

That is not the same thing introspection and reflection, introspection is the ability to access the object type, and object manipulation is a value reflecting the ability metadata attributes and / or functions

Python introspection commonly used functions

Python- introspection mechanism

Python introspection

Rookie Tutorial

Published 62 original articles · won praise 33 · views 10000 +

Guess you like

Origin blog.csdn.net/zjbyough/article/details/96037399