Introspection and reflection mechanism of python

Posted by dreamline on Fri, 12 Nov 2021 03:17:04 +0100

1, Introspection

Introspection means that when the interpretive language is loaded into memory, you can know the type of object and the methods under the object.

1.1 methods of self reflection

  • type()

    Gets the type of the object. This function can determine whether the object is a string, integer, list, dictionary, etc

    >>> type(1)
    	<type 'int'>
    >>> type("hello,world")
    	<type 'str'>
    >>> type([])
    	<type 'list'>
    >>> type({})
    	<type 'dict'>
    >>> class A():
    ...     pass
    >>> a = A()
    >>> type(a)
    	<type 'instance'>
  • dir()

    This function can return all property names and method names owned by an object

      # Returns all method names of a list instance
      >>> dir([])
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',  '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  • getattr()

    Gets the properties of the object

  • hasattr()

    Determine whether an object has a property

  • isinstance()

    Determine whether an object is an instance of a specific type or custom class

        >>> isinstance("python", str)  # Judge whether it is a string
        >>> isinstance(10, int)   # Determine whether it is of type int
        >>> isinstance(False, bool)  # Judge whether it is bool value
  • id()

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

    >>> a = "python"
    >>> id(a)
  • callable()

    Use callable to determine whether an object is callable, such as functions and classes. These objects are callable objects

    >>> callable("hello")
    >>> callable(str)

2, Reflection

A language that interprets types. When a program is loaded into memory to run, the process of obtaining information such as object types and properties in some way is called reflection.

Reflection can call object properties, methods and import modules through strings. It is a string based event driven

2.1 built in function with reflection capability

  • hasattr()

    It is used to detect whether the object contains a property named name. If so, it returns True. If not, it returns False

    class Cls():
        attr1 = 'attr1'
        def __init__(self, attr2):
            self.attr2 = attr2
        def meth1(self, num):
            return num**2
    obj = Cls('attribute2')
    print(hasattr(obj, 'attr1'))  # >>> True
    print(hasattr(obj, 'attr2'))  # >>> True
    print(hasattr(obj, 'meth1'))  # >>> True

    Both variables and methods are treated as "properties", so hasattr returns True

    # Determine whether an object's property is a method
    if hasattr(obj, "attr1"):
        if callable(obj.attr1):
            # attr1 is a method!
             # attr1 is not a method but an attribute
        # attr1 is not an attribute
  • getattr()

    getattr() is used to return an object property or method

    getattr(object, name[, default])

    • Object -- object.
    • name -- string, object attribute.
    • Default -- default return value. If this parameter is not provided, AttributeError will be triggered when there is no corresponding attribute.
    class A:   
        def __init__(self):   
   = 'zhangjing'  
         # self.age='24'
        def method(self):   
            print"method print"  
    Instance = A()   
    print(getattr(Instance , 'name, 'not find'))
    #If there is an attribute name in the Instance object, print the value of; otherwise, print 'not find'
    print(getattr(Instance , 'age', 'not find'))   
    #If there is an attribute age in the Instance object, print the value of self.age; otherwise, print 'not find'
    print(getattr(a, 'method', 'default')) 
    #If there is a method method, otherwise print its address, otherwise print default 
    print(getattr(a, 'method', 'default'))()   
    #If there is a method, run the function and print None; otherwise, print default  

    Usage scenario:

    obj = MyObject()
    for x in ['foo', 'bar']:
        # obj.x()  # There is no doubt that this is wrong.... So we can use getattr
        getattr(obj, x)()

    Implement the factory method with getattr: a module supports printing in html, text, xml and other formats, and calls different functions to realize output in several formats according to different incoming format parameters

     import statsout 
     def output(data, format="text"):                           
         output_function = getattr(statsout, "output_%s" %format) 
         return output_function(data)

In this example, you can call different methods of the statsout module according to the format parameters of the input output function (implement output%s with a formatted string)

  • setattr()

    The setattr() function corresponds to the getattr() function, which is used to set the attribute value. The attribute does not necessarily exist.

    setattr(object, name, value)

    • Object -- object.
    • name -- string, object attribute.
    • Value -- attribute value.
      >>class A(object):
      ...     bar = 1
      >>> a = A()
      >>> getattr(a, 'bar')          # Get property bar value
      >>> setattr(a, 'bar', 5)       # Set attribute bar value
  • delattr()

    Delete variables from the object. Note: cannot be used to delete methods

    class Person(object):
    	def __init__(self,name): = name
    	def talk(self):
        	print("%s Talking"

	p = Person("laowang")
    delattr(p,"name")       # Delete name variable
    print(           # An error will be reported