day24 reflection \ metaclass

Reflection reflect

# What is the reflection, in fact, introspection, self-examination of the meaning, refers to the reflection of an object should have, can detect, modify, add the ability to own property. 
# Reflection attributes is through string manipulation, four functions involved, four functions built-in function is normal, there is no double underline, there is no difference between print and so on.

Case

getattr setattr delattr the hasattr 

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

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

# 3. Add a new object attributes 
setattr (P, " ID " , " 123 " )
 Print (p.id) 

# 4. remove from the subject attribute 
delattr (P, " ID " )
 Print (p.id)

 scenes to be used:

# Reflection is actually the property of the additions and deletions to change search, but if the built-in __dict__ to operate direct use, 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 have to judge whether the object is to meet this requirement, 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 you must be provided to the object framework to work properly verified by the judge after judge verification is reflected do, 
of course, can be achieved by __dict__ are, in fact, the operation of these methods is carried out __dict__ packaging 
requirements: to implement the small frame for a terminal user's instruction processing is the frame has been achieved the most basic framework is that all projects are part of the same

 

Examples

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 the correct object it is necessary to use reflection to detect 
        # determines whether or not the object includes a method for processing the instruction 
        iF the hasattr (plugin, cmd):
             # remove the corresponding methods 
            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, the dead must write a class, that is unreasonable, because the other party can not know in advance what kind of place, and what is called class

Therefore, we should provide a framework for the user profile, ask for information tired of the configuration file, then the framework of their own to load the required modules

Skeleton code:

Import importlib
 Import Settings 

# 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 right objects need to use reflection to detect 
        # determines whether or not the object includes a method for processing the instruction 
        iF the hasattr (plugin, cmd):
             # remove the corresponding methods 
            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 object calls a plug-in framework to use it 
# wincmd = plugins.WinCMD () 
# partially outside the frame there is a custom object accomplished 

# frame obtained based on the class profile to get the desired 

path = settings.CLASS_PATH
 # from the configuration in separate out module class name and path 
the module_path, class_name = path.rsplit ( " . " ,. 1 )
 # get module 
mk = importlib.import_module (The module_path)
 # get class 
CLS = getattr (MK, class_name)
 # instantiate the object 
obj = CLS ()
# Invocation Framework 
run (obj)

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

 

Metaclass metaclass 

# What is Yuan class for class class is created, all things are objects, classes, 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 by default metaclass type.

 

Code

class the Person:
     Pass 
P = the Person () 

Print (type (P))
 Print (type (the Person)) 

the Person class is a class instantiated by type produced

Learning Objectives yuan class:

# Custom height of a class, such as the control class name must be a large hump in the way of writing 
classes 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 (metaclass), which covers the init method can achieve the demand 
of course, we can not modify the source code, so it should inherit the type to write your own metaclass, while covering init needs to complete

 

use

"" " 
As long as the inherited type then this class becomes a meta-class 
." "" 
# Defines a metaclass 
class MyType (type):
     DEF  __init__ (Self, clss_name, bases, dict): 
        . Super () __init__ ( clss_name, bases, dict)
         Print (clss_name, bases, dict)
         IF  not clss_name.istitle ():
             the raise Exception ( " Ah you can not write the name of the class ... " ) 

# specifies the metaclass for the pig class MyType 
class Pig (= the metaclass that MyType):
     Pass 

class Duck (= the metaclass that MyType):
     Pass

The call metaclass

# 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 will not be able generating object, 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 covers the method call 
when you want to create a process control class, you cover the init method

 

Case:

To achieve the objects of all the attribute names to uppercase

lass MyType(type):
    def __call__(self, *args, **kwargs):
        new_args = []
        for a in args:
            new_args.append(a.upper())

        print(new_args)
        print(kwargs)
        return super().__call__(*new_args,**kwargs)


class Person(metaclass=MyType):
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender

p = Person(name="jack",gender="woman")
print(p.name)
print(p.gender)

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 override this method it must be ensured, new methods must have and must return value is the class corresponding to the object

 

test

class Meta (of the type): 

    DEF  __new__ (CLS, * args, ** kwargs):
         Print (CLS) # metaclass own 
        Print (args) # create several parameters required for the class name of the class, the base class, namespaces 
        Print (kwargs ) # empty 
        Print ( " new new RUN " )
         # return Super () .__ new new __ (CLS, * args, ** kwargs) 
        obj = of the type. __new__ (CLS, * args, ** kwargs)
         return obj
     DEF  __init__ (Self, A, B, C): 
        . Super () the __init__ (A, B, C)
         Print("init run")
class A(metaclass=Meta):
    pass
print(A)

 

Init summary of new methods and process control can be implemented to create a class, init easier

Singleton design pattern

```

? Design patterns for some fixed routines to solve problems 
such as: MVCMTV and other 
singleton: refers to a class to produce an object 
Why use Singleton: Singleton is to save resources, when all object properties of a class of all the same it is not necessary to create multiple objects

Yuan class implementation:

# Singleton n metaclass 
class Single (type):
     DEF  the __call__ (Self, args *, ** kwargs):
         IF the hasattr (Self, " obj " ): # determines whether or not there has been some target 
            return getattr (Self, " obj ' ) # have returned 

        obj = Super (). __call__ (* args, ** kwargs) # do not create 
        Print ( " new new up " ) 
        self.obj = obj # and stored in class 
        return obj 


class Student (the metaclass that =SINGLE):
     DEF  __init__ (Self, name): 
        self.name = name 


class the Person (the metaclass that = SINGLE):
     Pass 

# will create an object 
the Person () 
the Person ()

 

 

 

aa

 

Guess you like

Origin www.cnblogs.com/Ryan-Yuan/p/11272612.html