reflection in Python

Python Methods and Functions

Using reflection, we can write one recursive inverse function that will work with strings, lists, and any other sequence that supports slicing and concatenation. If obj is a string reference, then Python will return an object of type str. Further, if we write str (), we get a string, which is an empty string. In other words, writing str () — this is the same as spelling "". Similarly, writing list () — this is the same as writing [].

# Python program to illustrate reflection

def reverse (seq):

  SeqType = type (seq)

emptySeq = SeqType ()

  

  if seq = = emptySeq:

return emptySeq  

 

restrev = reverse (seq [ 1 :])

  first = seq [ 0 : 1 ]

 

# Merge result

result = restrev + first

 

return result

 
# Driver code

print (reverse ([ 1 , 2 , 3 , 4 ]))

print (reverse ( "HELLO" ))

Output:

 [ 4,3,2,1] OLLEH 

Reflective functions

Reflective functions include type (), isinstance (), callable (), dir () and getattr ().

  1. type and origin — see

    Output:

     x is not callable y is callable 

    called when used in OOP

     class Foo1: def __call __ (self): print ('Print Something') print (callable (Foo1)) 

    Exit:

     True 
  2. Dir: The dir () method attempts to return a list of valid object attributes. Dir () tries to return a list of valid object attributes.
      If the object has a __dir __ () method, the method will be called and should return a list of attributes.
      If the object does not have method __dir () __, this method tries to find information from the __dict__ attribute (if defined) and from the type object. In this case, the list returned from dir () might not be complete.

Examples :

 number = [1 , 2,3] print (dir (number)) characters = ["a", "b"] print (dir (number)) 

Output:

  • Getattr: The getattr () method returns the value of the named attribute of the object. If not found, it returns the default value supplied to the function. The getattr method takes three parameters object , name and default (optional).
     class Employee: salary = 25000 company_name = "pythonengineering" employee = Employee () print ('The salary is:', getattr (employee, "salary")) print ('The salary is:', employee.salary) 

    Output:

     The salary is: 25000 The salary is: 25000 
  • Links
    2.
    docs_python
    3. wiki books

    This article courtesy of Subhajit Saha . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





    Tutorials