Python object-oriented | reflection

 

1. What is reflected
  mainly refers reflection program can access, modify, and detect its own ability state or behavior (introspection).

2. python reflective object-oriented: the object-related properties operated by a string. Everything is an object in python (could use reflection)


Four built-in functions:

hasattr (obj, attr): 
  This method is used to check whether there obj value of the attribute named attr, it returns a Boolean value.

getattr (obj, attr): 
  Calling this method returns the obj named attr value value of the property , for example, if attr is 'bar', the obj.bar returns.
setattr (obj, attr, val) 
:   value will call this method of obj named attr attribute assigned to val. For example, if attr is 'bar', corresponding to the = Val obj.bar
delattr (obj, name)
  which function to delete a specified by the obj string attribute . delattr (x, 'foobar') = del x.foobar

 

The instantiation object reflector

class Foo:
    F = ' static class variable ' 
    DEF  the __init__ (Self, name, Age):
        self.name=name
        self.age=age

    def say_hi(self):
        print('hi,%s'%self.name)

obj=Foo('Tony',18)

# Detect whether it contains a property 
Print (the hasattr (obj, ' name ' ))                   # True 
Print (the hasattr (obj, ' say_hi ' ))                 # True

# Get property 
Print (getattr (obj, ' name ' ))                   # Tony 
Print (getattr (obj, ' say_hi ' ))            # <Method Foo.say_hi of bound <__ main__.Foo Object AT 0x00000219B4CF6688 >> 
Print (getattr (obj, ' AAAAAAAA ' , ' does not exist ah ' ))    # absence ah If no settings will be given

# Set the properties 
setattr (obj, ' John ' , True)
setattr(obj,'show_name',lambda self:self.name+'')
print(obj.__dict__)     # {'name': 'Tony', 'age': 18, 'John': True, 'show_name': <function <lambda> at 0x000001E56C6AC048>}
print(obj.show_name(obj))                   # Tony君

# Delete attributes 
delattr (obj, ' Age ' )
delattr (obj, ' SHOW_NAME ' )
 # delattr (obj, 'show_name111') # does not exist, an error 
Print (obj. the __dict__ )                          # { 'name': 'Tony', 'John': True}

 

Of the class of reflection

class Foo(object):
    staticField = "old boy"

    def __init__(self):
        the self.name = ' wupeiqi '

    def func(self):
        return 'func'

    @staticmethod
    def bar():
        return 'bar'


Print (getattr (Foo, ' staticField ' ))         # Note whether the second parameter is a static property, the object properties, methods, every single quotation marks '' 
Print (geattr (Foo, ' FUNC ' ))
 Print (getattr (Foo , ' bar ' ))

 

Reflected current module

Import Time           # a py file is a module 
time.time ()

if hasattr(time,'time'):
    print(time.time)
    print(getattr(time,'time')())

'''
Perform output:
<built-in function time>
1569572942.545881
'''

 

import sys
def s1():
    print('s1')
def s2():
    print('s2')

current_module = sys.modules[__name__]
print(current_module)
print(hasattr(current_module, 's1'))
print(getattr(current_module, 's2'))

'''
Perform output:
<module '__main__' from 'C:/Users/Administrator/Desktop/temp/test.py'>
True
<function s2 at 0x0000026BFDF98048>
'''

 

 

Reflecting light of other modules

"""
Program Category:
    module.py
    test.py
"""


# Module module.py code in 
class A:
    name = "module"

    DEF FUNC ():
         Print ( ' I am func module module ' )


# Test.py code 
Import Module

# 方法一:
clas = getattr(module, 'A')
print(clas.name)                    # module

# Method two: 
Print (getattr (module.A, ' name ' ))     # Module 
getattr (module.A, ' FUNC ' ) ()          # I am func module module

 

Suppose you have a file name userinfo, you need to be renamed

# The first: Conventional way 
Import os
os.rename('userinfo','user')

# The second: the use of reflective 
Import os
getattr(os,'rename')('userinfo','user')      # getattr(os,'rename') 相当于os.rename

 

to sum up:

1. Class Name Class namespace using getattr (class name, 'name')
  

2 can be the object using the object's methods and properties getattr (object name, 'name')
  

3. Use their name from their location in the module SYS Import
  

  getattr ( the sys.modules [ '__ main__'] , name)

4. The module name in the module import module
 

  getattr (module name, 'name')

import them;
getattr(os,'rename')('user','user_info')

Guess you like

Origin www.cnblogs.com/Summer-skr--blog/p/11801457.html