Beginner python road -day29

1. Moto类

# Metaclass: 
in python, are all object classes are objects, a class can be used as ordinary objects, such as a storage to the list, or as an argument to a function, etc ... 
Since the object class is instantiated generated, and the class object is a metaclass (type) produced by instantiating 
metaclass: means for generating class class a class consists of three parts
1 . name of the class 2 class class Fathers 3 class namespace when we define a class, using the type (class name, parent class tuple namespace dictionary) method to obtain a class type (class name, parent class tuple namespace dictionary) # returns a new class type (the object) # will return the object type and therefore when using the class definition of class, the interpreter method will automatically call the instantiation of the type
Exec 

Exec for carrying out a string of python code that they meet the python can execute, and you can specify the name of the execution generated into a namespace 

class_text = "" " 
class A: 
    DEF the Test (Self): 
        Print (Self) 
"" " 
loca2 = {}
 exec (class_text, None, loca2)
 Print (loca2) 

hence the exec is another method to obtain class methods 


eval for performing simple expression, you can not have any special syntax, one line of code
Custom metaclass:
 =======
 # #### metaclass translated as: metaclass sight of it should think this is the metaclass 

we try to add MetaClass easy to read after the class name in the class definition meta 

application : 

when we need highly customized categories, such as restrictions on the class name must start with a capital and so on ... 

you need to use metaclasses, but metaclass type in the code can not be modified, only create new meta-class (inherited from type) by covering ` the __init__ ` class to complete the restriction 

class MyMetaClass (type):
     pass 

# use a custom metaclass 
class the Person (= the metaclass that MyMetaClass):
     pass
__init__ method 

automatically executed when the class object is instantiated ` __init__ ` methods, classes are objects, when an object instance of the class is performed automatically metaclasses ` __init__ ` method 

and necessary parameters into three classes, class name, parent class who namespace 

of course, will automatically pass the class object itself as the first parameter   

# # case: limit class name must be capitalized control class method name must be all lowercase 
class MyMetaClass (of the type):
     DEF  __init__ ( Self, class_name, bases, name_dict): 

        . Super () __init__ (class_name, bases, name_dict)
         # class name must be capitalized or directly thrown 
        IF  not class_name.istitle ():
             Print ( " class name must be capitalized silly x ! " )
             the raise Exception 

        # control class method name must be all lowercase 
        forK in name_dict:
             IF STR (type (name_dict [K])) == " <class 'function'> " :
                 IF  Not k.islower ():
                     The raise Exception
     Pass 

# automatically calls the __init__ method which pass metaclasses the class object itself class name of the parent class are namespace 
class Student (Object, the metaclass that = MyMetaClass): # MyMetaClass ( "Student", (Object,), {}) 
    nAME = 10 DEF say (Self):
         Print ( " sAY " )
     Pass
    
__new__ Method : 

class new method will be executed when the class object is created, and before the init method of   

action is to create a class object    

class A (= the metaclass that MyMetaClass):     
Pass
 
. 1 . MyMetaClass perform the method to get a __new__ class object 
 2 . __init__ method of execution MyMetaClass incoming class of objects, and other properties, initialized 

Note: 1 . If the cover __new__ certain type of call should __new__ and returns the results
 2. in the call the init method before class object has been created, so if the high-performance requirements, then you can choose at the completion of the new custom if there are problems, they do not create a class object
__call__ method : 

Call metaclass will be executed by invoking the class object is instantiated, the object can be used to control the process of creating 


class MyMeta (of the type): 

    # get an instance of a class 
    DEF  __call__ (Self, * args, * * kwargs):
         Print ( " Call " )
         # return Super () Call .__ __ (* args, ** kwargs) 
        new_args = []
         for I in args:
             IF the isinstance (I, STR): 
                new_args.append (i.upper ( )) 
            the else : 
                new_args.append (I) 
        return . Super () the __call__ (new_args *, ** kwargs)



# Note Note Note: __new__ __init__ is also performed when creating a class object 
# execute when __call__ class object to generate instances 

class Student (the metaclass that = MyMeta):
     DEF  __init__ (Self, name, Gender, Age): 
        self.name = name 
        Self .gender = Gender 
        self.age = Age 

S = Student ( " Jack " , " Woman " , 18 is )
 Print (s.age)
 Print (s.gender) 


class the Person (= the metaclass that MyMeta):
     DEF  the __init__  (Self, name, gender):
        the self.name= name
        self.gender = gender

p = Person("rose","man")
print(p.name)
Summary: The
 process of creating class with control ** __ ** __init 
** Examples of process control objects using __call__   also need to call the type of __call__ and returns its result **      
** __new__   will first perform in __new_ in __init__ _ must call type and returns the result of __new__ **
Yuan class implements the singleton pattern 

What is the Singleton: 

a class if there is only one instance of an object, the class became a singleton class 

benefits of a single case: 

when all the characteristics and behavior of objects of a class exactly the same, to avoid duplication create objects, waste of resources 

case: 
class SingletonMetaClass (of the type):
     # when you create a class for each class will perform a set init obj property defaults to None in this for the 
    DEF  __init__ (Self, a, b, c): 
        . Super () __init__ (a, B, C) 
        self.obj = None 
    
    # executes the method when the class object to be created 
    DEF  the __call__ (Self, args *, ** kwargs):
          # determines if this class instance has a direct return to achieve singleton 
        IF self.obj:
             return self.obj 

        # no new instance is created and saved to the class 
        obj = type.__call__(self,*args,**kwargs)
        self.obj = obj
        return obj

2. Abnormal

Exception: 
abnormal is abnormal happens during program execution, is a wrong signal when the occurrence of 

an exception if not handled properly, it will cause the program to be terminated, that the user experience is very bad, can lead to serious consequences   

processing the purpose of the program is to improve abnormal robustness 

abnormal Category: 
Python interpreter will first check the syntax before the code is executed, syntax checking, code execution will start by

 1 syntax detect anomalies: as a qualified programmer should not appear this species lower error

 exception 2. run time: syntax check has passed, starts executing the code, called an exception occurs during the execution of the operation abnormality
Abnormal common example: 
TypeError: ' int ' Object IS  Not subscriptable object can not be sliced   
TypeError: ' List ' Object IS  Not Callable object can not be invoked 
IndexError: list index out of range index out of bounds 
TypeError: ' builtin_function_or_method ' Object IS  Not Iterable objects can not be iterated 
a KeyError: ' XXX '       this key does not exist 
FileNotFoundError: [Errno 2] no SUCH File or Directory: ' XXXXX '  File not found 

unusual composition: 

Traceback (MOST recent Results Last Call): 
  File " F:. / On Day 29/11 common exceptions .py " , Line 22, in <Module> 
    with Open ( " XXXXX " ) AS f: 
FileNotFoundError: [Errno 2] No SUCH file or Directory: ' XXXXX ' 

        
Traceback abnormal tracking information for a specific location and display an error occurred during the call 
, including the line number of the module file path name of the function of the specific code errors occur 

in front of the last line is the type of error   
         details behind the error when the main reference is to find errors Details exception handling:
    

After the exception occurs if incorrect would cause the program to terminate, we should try to avoid abnormal

Syntax:
 try : 

may appear abnormal code into try inside 

except specific types of exceptions as e: 

If you really abnormal executed except 

to handle exceptions:
 1 . When the error is not the cause of the disturbance stand Makati try first to identify and solve it  

 2. the try only in even if you know why the error occurred, but you can not avoid   
   , for example, you need to explicitly tell the user a correct file path, however the user still passed the wrong path    

   , such as socket sides have to use the pipeline, but if one party has For some reason forced to close, even if you know the reason can not avoid making mistakes it can only try to ensure the program ends normally       

   in a nutshell: can not increase without try try

   
# # Custom exception class: 
When the system provides an exception class can not accurately describe the error cause can custom exception class  
 class   MyException (Exception):
     Pass 
inherited from Exception to 

take the initiative to throw an exception: 
When we do function provider, to the outside world provides a functional interface, but the user does not follow the appropriate way to use, or incorrect parameter type and other reasons, leading to normal when the function can not be performed, they should take the initiative to throw an exception 

: use the keyword raise 
keyword of any Exception subclass or objects 
The raise MyException
 The raise MyException ( " error specific reason! " )
Assert assert: 
assertion can actually be understood as meaning conclude   

that is very definitely a certain condition is true 

whether the conditions established in fact can be used to determine if 

the purpose of its existence is to simplify determine if born

 

Guess you like

Origin www.cnblogs.com/wangwei5979/p/10931201.html