--- reflective object-oriented programming

Reflection (the reflect)

What is a reflection, in fact, introspection, self-examination of the meaning of

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

It is reflected by the string operation property

Design four functions, these four functions is the common built-in functions, not underlined, and print and so no difference.

getattr setattr delattr the hasattr 

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

STU = Student ( ' Uu ' , 12 is )
 IF the hasattr (STU, ' name ' ): # determination target whether there is an attribute
     Print (getattr (STU, ' name ', None )) # attribute taken from the subject, the third return to the default value when the default values attribute does not exist 
# adding new attributes for the object 
setattr (stu, ' Gender ' , ' MALE ' )
 Print(stu.gender) 
# remove attributes from the object delattr (STU,
' name ' ) Print (stu.name)

scenes to be used:

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

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 that you provided to the object framework, it is necessary to use properly verified by the judge after judge verification is reflected things to do, of course, also be achieved by __dict__, in fact, these methods of operation that is carried out __dict__ package

"" " Demand: To achieve a small frame for processing user terminal instructions " ""
# Settings 

# the file as a profile frame 
# as your user frame with the frame specified in the configuration file of the class which 
CLASS_PATH = ' libs.plugins.WinCmd '
# Libs.plugins 


# class wincmd: 
# 
#      DEF cd (Self): 
#          Print ( 'wincmd change directory') 
# 
#      DEF the Delete (Self): 
#          Print ( 'wincmd delete') 
# 
#      DEF dir (Self): 
#          print ( 'list directory') 
# 
# class LinuxCmd: 
# 
#      DEF cd (Self): 
#          print ( 'Linux change directory') 
# 
#      DEF the delete (Self): 
#          print ( 'Linux delete') 
# 
#      DEF LS (Self): 
#          Print ( 'list directory')
Import Settings
 Import importlib 
part # framework has been implemented 
DEF RUN (obj):
     the while True: 
        cmd = the INPUT ( ' Please enter the 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 (obj, cmd):
      # extraction method corresponding RES
= getattr (obj, cmd) RES () # to perform a method of processing instructions the else : Print ( ' NONO ' ) Print ( ' end ' ) # prepared according to the frame configuration files to get the necessary classes
# separate out from the configuration module class name and path modles_path, cls_name
= settings.Class_path.rsplit ( ' . ' ,. 1 )
# get module mk
= importlib.import_module (modles_path)
# get class CLS
= getattr (MK, cls_name)
# instantiate the object obj
= CLS ()
# call frame run (obj)

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

Metaclass (the metaclass that)

What metaclass is used to create a class of class

Everything is an object, the object class course

The object is generated by instantiating the class, if the class is an object, it certainly has a class object is generated by another class instantiation

All classes are by default metaclass type

verification:

class Person:
    pass

p = Person()
print(type(Person))  # <class 'type'>

Learning Objectives yuan class:

The height of a custom class, for example, control the class name must be written in large hump manner

Classes are objects, also have their own class

"" " Requirements: Creating a class object to do some limitations " "" 

# defines a metaclass 
class MyType (of the type):
     DEF  __init__ (Self, cls_name, bases, dict): 
        . Super () __init__ (cls_name, bases, dict)
         Print (cls_name, bases, dict)
         IF  not cls_name.istitle:
             the raise Exception ( ' ! Please follow the rules ' ) 

specifies the metaclass for the class MyType as Pig 
class Pig (the metaclass that = MyType)
     Pass 
#   Pig () { '__module__': '__main__', '__qualname__': 'Pig'} 

class Pig (= the metaclass that MyType):
    pass
# Error Exception: Please follow the rules!

Metaclass call method:

__call__ execution timing function: This method will automatically trigger the execution (Object parentheses) when calling the object

class Foo:
     DEF  __call__ (Self, * args, ** kwargs):
         Print ( ' RUN ' ) 

f = Foo ()   # call Foo objects get f 
f ()   # trigger __call__ is performed when the calling object

Usually calls a normal object is meaningless, that __call__at what time to use it?

We say that the class is an object, then Foo () is not also perform the Foo class of__call__ function?

Who Foo class is it? Default metaclass type, as specified by mateclass custom metaclasses to test

# Test 
class A (type):
     DEF  the __call__ (Self, args *, ** kwargs):
         Print ( ' RUN ' )
         Pass 
    Pass 

class B (= the metaclass that A):
     Pass 

Print (B ())
 # output RUN 
# output None

Precautions coverage __call__ function

  The first line shows the output when calling Classes B, indeed __call__ function is performed automatically,

  The second line prints a blank, which is why?

  You must explicitly create an object of the process: first create an empty object, to perform initialization attributes stored in the object's name space!
  So this must be done in two steps __call__ function, while the completion of initialization of the object is returned to the caller

  Once the cover __call__ function, you must own to complete the above steps

class MyMeta(type):
    def __init__(self,name,bases,dict):
        super().__init__(name,bases,dict)
        print('run')

    def __call__(self, *args, **kwargs):
        print('元类 call')
        print(self)
        print(args)
        print(kwargs)

        return super().__call__(*args,**kwargs)

class Dog(metaclass=MyMeta):

    def __init__(self,name):
        self.name = name

    def __call__(self, *args, **kwargs):
        print('Dog run')

d = Dog('dahuang')
print(d.name)

# 输出结果
#run
# 元类 call
# <class '__main__.Dog'>
# ('dahuang',)
# {}
# dahuang
# Must pass through keyword parameter 

class Metaclass (of the type):
     DEF  __call__ (Self, * args, ** kwargs): 
    
        IF args:
             The raise Exception ( ' must be in the form of keywords mass participation ' )
         return Super (). the __call__ (* args, ** kwargs) 


class A (= the metaclass that Metaclass):
     DEF  the __init__ (Self, name): 
        the self.name = name 

A = A (name = ' Uu ' )
 Print (a.name)

The new method metaclass

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 __Init__ to initiate operation of the class

Note: If you override this method it must be ensured, new methods must have and must return the value corresponding to the class object

class Meta (of the type): 

    DEF  __new__ (CLS, * args, ** kwargs):
         print (CLS) # metaclass own 
        print (args) # create several parameters (class name, base class, namespaces) class needs of 
        print (kwargs) # empty 
        Print ( ' new new RUN ' ) 
        obj = type. __new__ is (CLS, args *, ** kwargs)
         return obj 

    DEF  the __init__ (Self, a, B, C): 
        Super (). the __init__ (a, B, C)
         Print ( ' RUN ' )

class A(metaclass=Meta):
    pass

# a = A()
print(A)

Init summary of new methods and ways of achieving control of the process of creating the class, init easier

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

Singleton design pattern

Design patterns for some fixed routines to solve problems

MVC     MTV

Singleton: refers to a class object is to produce a

Why use singleton:

Singleton in order to save resources, when all the object properties of a class all the same, it is not necessary to create a plurality of objects

# 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 ()

 

Guess you like

Origin www.cnblogs.com/KrisYzy/p/11271539.html