Day24 ---- Shanghai the reflecting object oriented metaclass

table of Contents

  • reflection

  • Moto类

 

 

A reflective

What is reflection?

Reflecting means should have an object can be detected, modify, increase their ability to attribute

It is reflected by the string operation property

Involving four functions: getattr setattr delattr

This function is an ordinary four built-in functions without the double underline, there is no difference between print and so on

Case:

class the Person:
     DEF  the __init__ (Self, name, Age): 
        the self.name = name 
        self.age = Age 

P = the Person ( " Jack " , 18 is, " man " ) 

# IF the hasattr (P, "name"): #. 1 the judgment whether or not an object exists a property 
#      Print (getattr (P, "names", None)) # 2. remove from the object attribute, the third attribute value of the bit is not present a default value when the default value is returned 

# 3 adding a new attribute for the object 
setattr (P, " ID " , " 123 " )
 Print (p.id) 

# 4. remove from the subject attribute 
delattr (p,"id")
print(p.id)

scenes to be used:

Reflection of the fact that the property additions and deletions to change search, but if the direct use of the built-in dict to operate, grammar cumbersome, difficult to understand

Another major problem is that if the object is not my own writing is provided by the other party, I would have to determine whether the object is to meet the requirements, that is, properties and methods if I need

Frame design approach:

Skeleton code:

"" " 
Reflection is known as the cornerstone of the framework, why 
because the designers framework, it is impossible to know in advance how your objects in the end is designed 
so the object you must provide the framework to use to pass judgment after normal verification 
judgment is reflected to verify do, 
of course, can be achieved by __dict__ are, in fact, the operation of these methods is carried out __dict__ packaging 
requirements: to achieve a small frame for processing user terminal command 
frame has been achieved is the most basic framework is that all projects are part of the same 
"" " 

Import plugins 

# portion of the frame has been achieved 
DEF RUN (plugin):
     the while True: 
        cmd = the iNPUT ( " Please enter command: " )
         IF cmd == " Exit " :
             BREAK 
        # because the user can not determine whether the incoming frame is required to use the right object to detect reflected 
        # determines whether the object includes a method for processing the instruction 
        ifthe hasattr (plugin, cmd):
             # extraction methods corresponding to 
            FUNC = getattr (plugin, cmd) 
            FUNC () # to perform a method of processing instructions 
        the else :
             Print ( " the command is not supported ... " )
     Print ( " See you La La ! " ) 


# create an object invocation framework plugin to use it 
# wincmd = plugins.WinCMD () 
# partially outside of the framework have custom objects to complete the 
Linux = plugins.LinuxCMD () 
RUN (Linux)

Plug part:

class wincmd: 

    DEF cd (Self):
         Print ( " wincmd change directory .... " ) 

    DEF the Delete (Self):
         Print ( " wincmd or not to delete the library on foot? " ) 

    DEF dir (Self):
         Print ( " wincmd lists all the files .... " ) 

class LinuxCMD: 

    DEF cd (Self):
         Print ( " Linuxcmd change directory .... " ) 

    DEF RM (Self):
         Print ( " ? Linuxcmd or not to delete the library on foot " ) 

    defLS (Self):
         Print ( " Linuxcmd lists all the files .... " )

The frame code is written dead must use a class, it is unreasonable, because they can not know in advance the other classes where and what kind

Therefore, we should provide a framework for the user's profile, ask the accumulated information to the configuration file

Then frame themselves to load the required modules.

Profile Code:

'' ' For a profile, providing a path like ' '' 
CLASS_PATH = " libs.plugins.WinCmd "

Finally, the framework code:

# The main function of the program frame 
Import the importlib
 Import Settings 


DEF RUN (plugin):   # receiving plug-in as parameter, which actually refers to the class of the object instance WinCmd 
    the while True: 
        cmd = INPUT ( ' Enter command: ' ). Strip ()   # cmd command refers to your own input, which is the method we defined in the class. 
        IF cmd == ' Exit ' :
             BREAK 
        # determines whether there is a subject which 
        IF the hasattr (plugin, cmd):
             # removed and performs the process 
            FUNC = getattr (plugin, cmd) 
            FUNC () 

    Print ( 'you See! ' ) 

# create a plug-in object, call the main frame to use 
# linuxcmd = plugins.LinuxCmd () # instantiate the object as a plug 
# RUN (linuxcmd) # main function calls the object 
' '' 
Ask a question? While we can call the object with the framework, but we do not know the class is instantiated object, I do not know where the package where! 
I.e. linuxcmd = plugins.LinuxCmd () and packet class LinuxCmd plugins do not know where 
 the solution: introducing dynamic module. . . 
'' ' 
# Get the module from the configuration file name and class 
path = settings.CLASS_PATH 
model_path, cls_name = path.rsplit ( " . " ,. 1)   # string cutting, extracting assignment 
# Print (cls_name) 
# Print (model_path) 
importlib.import_module = PL (model_path)   #Where to find the class module, receiving pl variable name 
CLS = getattr (pl, cls_name)   # find classes by getattr method, receiving CLS 
# Print (CLS) 
obj = CLS () 
RUN (obj)

In this way, the framework and implementation of the code will completely decoupled, leaving only the configuration file.

Second, reflection and dynamic import module

The code reference Solution: import module using module importlib

'' ' 
When we use the framework, you can not know in advance the relevant information provided by the class. So we use dynamic import module to obtain information 
'' ' 
Import importlib   # Import Import Module 

# to prevail currently executing file import plug-in modules where 
PL = importlib.import_module ( " libs.plugins " )
 ' '' 
PL = importlib. import_module ( "libs.plugins") 
Why use this code to receive pl? 
Because we are import libs package plugins module, so that in the current namespace execution file gave rise to a point plugins module name, 
and that name is a variable, we used to receive the pl! 

'' ' 
Print (PL)
 # result: <module' libs.plugins' from ' H: \\ PycharmProjects \\ Py_learn_2 \\ \\ libs practice day24 \\ \\ 3 plugins.py'> 
# we found a module on values can be found under the name of the class in the class module, 

CLS = getattr (PL,)   # Everything object, we can be seen as the class of object modules plugins using getattr method 
Print (CLS)   # <class 'libs.plugins.WinCmd'> 

# instantiated objects generated 
obj = CLS ()
 # object invokes methods 
obj.cd ()

Third, Moto类

What is a metaclass?

It is to create a class of class!

What is a class object?

In Python Everything object class is of course the object, the object is created by instantiating the class, if the class is an object, it certainly is another class object class is instantiated generated all classes are default metaclass type

Case:

class Person:
    pass
p = Person()
print(type(p))  # <class '__main__.Person'>
print(type(Person))  # <class 'type'>

Yuan class action?

Can be a custom class height,

For example: the control class name must be a way to write large hump

Example: When you create a class specified class name first letter capitalized

Ideas are as follows:

'' ' 
Categories are objects, also have their own class, 

our demand is to create a class object to do some limitations 

thought initialization method we just find the class object class (class yuan), covering in which init method can achieve the demand 

of course, we can not be modified source code, so it should inherit the type to write your own metaclass, while covering init to complete the requirements 
' ''

Code:

# Because type class we can not change, so I we want to customize the metaclass 
class MyType (type):
     DEF  __init__ (CLS, cls_name, bases, dict): 
        . Super () __init__ (cls_name, bases, dict)
         Print (cls_name, bases, dict)
         IF  not cls_name.istitle (): 

            The raise Exception ( ' class name to the capital ... I remember! ' ) 

# Specifies the metaclass 
class the Person (the metaclass that = MyType):
     Pass 
# execution results: Exception: class name capital. . . For remember!

Method metaclass __call__

'' ' 
When you call a class object will automatically treasure __call__ methods yuan class, and as the first argument to the class itself, as well as a bunch of parameters behind 

after covering metaclasses call, this class can not produce objects, you must call the super () .__ call__ to complete the creation of the object   
and returns its return value 

'' '

scenes to be used:

When you want to control the process of creating an object, it covered call method

When you want to create a process control class, they cover the init method

Case:   

To achieve the objects of all the attribute names to uppercase

"" " The object of all attribute names all uppercase " "" 
class Mytype (of the type):
     DEF  __call__ (CLS, * args, ** kwargs): 

        new_args = []
         for i in args: 
            i = i.upper () 
            new_args.append (I) 

        Print (new_args)   # [ 'JASON'] 
        Print (kwargs)   # {} 
        return Super (). the __call__ (new_args *, ** kwargs) 


class the Person (= the metaclass that Mytype):
     DEF  the __init__ (self,name):
        the self.name = name

p = Person('jason')
print(p.name)   # JASON

Note: Once the covered call must call the call the parent class method to generate the object and return the object

Supplement new method

"" " 
When you want to create a class object, the method will be executed first __new__ yuan class, get an empty object, and then will automatically call the __init__ to initialize the operation of this class   
Note: If you cover this method it must be ensured, new methods must have and must return a value that corresponds to the class object 
"" "

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/qinsungui921112/p/11272601.html