python--anomaly and reflection in object-oriented discourse

Source: Internet
Author: User
Tags print object

  1. Built-in functions Isinstance and Issubclass

    1.1 Isinstance Usage:
    1 isinstance (STRING,STR)


    Determines whether the first parameter is a subset of the second parameter, for example:

    1 PrintIsinstance ("Test", str)#determine if test is a string type2 3C:\Python27\python.exe d:/python/s11/8day/Reflex/test.py4 5 True6 7 8 PrintIsinstance (123,int)#determine if 123 is an integral type9 TenC:\Python27\python.exe d:/python/s11/8day/Reflex/test.py One  ATrue
    You can also determine whether an object is an instance of a class, and return a Boolean value

    1.2 Issubclass Usage:
    1 issubclass (sub, super)

    A derived class that determines if a sub is super, and the return value is also a Boolean value

    Note: Using Isinstance and Issubclass destroys the polymorphism of the object


  2. Exception handling
    Python throws an exception after encountering an error, and if the exception object is not handled or captured, the rendering terminates the execution of the program with so-called backtracking (Traceback), as follows:
     1  C:\Python27\python.exe d:/python/s11/8day/Reflection/ test.py  2  traceback (most recent call last):  3  File  d:/python/s11/8day/test.py  , line, in  <module>< Span style= "color: #008080;" >4  print   Isinstance (d,int)  5  nameerror:name  " d   '  

    In Python, each exception is an instance of class exception, and exception can be said to be the base class for all exceptions. If we catch the error and deal with it, the whole program does not backtrack but continues to execute.

    2.1 Passive exception
    That is, the code is written in the try block, when the program is automatically triggered when the error, except is responsible for capturing and handling exceptions, the use of the following

    1 Try : 2      code block 3except exception,e:    # E is an instance of exception, an object; The error message above is encapsulated in E 4      Exception handling          # Here you can print exception information, such as (print e), or you can do other things like write exception information to the log

    It is important to note that if you print E, because the print object is normally returned as the memory address of the object, and in exception handling, when you print the object, you will call exception's __str__ method, returning the exception information instead of returning the memory address. So you don't have to be surprised when you print and you find that the information is abnormal.


    When except catches an exception, you can also add a except behind the except, just like the tap water filter to capture a specific exception in a layer

    1 Try:2 code block3 exceptKeyerror,e:#attempting to access a key that does not exist in the dictionary4     Printe5 exceptValueerror,e:#Pass in a value that is not expected by the caller, even if the value is of the correct type6     Printe7 exceptException,e:#If you can't anticipate what's going to happen, well, we have a Magnum anomaly .8     PrintE


    Another way to do this:

    1 Try : 2     Garen = Hero3except (keyerror,valueerror), E:    # written in tuple form 4      Print E



    2.2 Active Trigger exception
    It is not triggered until the program code encounters an error, but we trigger it ahead of time where the problem is expected to occur.

    1 Try : 2     Raise Exception (' error here ')      #提前传参并实例化异常 3except  Exception,e:                    #把错误信息封装到exception的实例e里 4     print E


    2.3 Custom Exceptions
    is not only our own definition of the exception trigger conditions and processing methods, the creation of custom exceptions need to directly or indirectly inherit exception

    1 classTesterror (Exception)://inherit exception exception base class2     def __init__(self,msg=None):3Self.msg =msg4     def __str__(self):5         ifSELF.MSG://Dynamic display of exception information based on parameters passed in6             returnself.msg7         Else:8             return "Custom Exceptions"Default exception Display information


    Calling custom Exceptions

    1 Try : 2     raise testerror ()   // Instantiate the custom exception class, followed by parentheses to pass in parameter 3except  testerror,e: 4     Print E

    2.4 Finally
    The Close method can be placed in the finally clause, regardless of whether an exception occurs in the TRY clause, such as when you are reading or writing a file or scoket communication, whether or not an exception should be closed after closing the file or the network socket.

     1  try  :  2  f = open ( " test.txt  , "  a   "    )   F.write (data)  4  except   exception,e:  5  print   e  6  finally  :  7  f.close () 

    2.5 Ignore All exceptions
    1 Try : 2     Garen = Hero3except:4     pass

    This is a more dangerous usage, ignoring all exceptions to the program and continuing to let the program execute.


    exception Handling just one point to remember: when we know that a piece of code might cause some kind of exception, but we don't want the program to stop, we can add exception handling as needed.

    Extension: The internal implementation of GetAttr in reflection is also achieved by accessing the attributes and capturing the ATTRIBUTEERROR exception areas that can be thrown.


  3. Reflection
    Reflection, the name into a verb, this is the author after reading "execution in the kingdom of nouns" after the reflection of the first reaction, we are interested to go through, an article is not too long.

    Let's imagine a scene like this: You sit at the computer, play lol, pass the message through the mouse and keyboard, and the hero in the game makes the corresponding action, which can be seen as reflection. How did this happen? Let's take a look at the following:

    First we define a hero template, which is the base class.
    1 classHero:2     def __init__(self):3Self. ATK = 304Self. DEF = 105Self. HP = 3006Self. MP = 1007 8     defWalk (self):9         Print "your hero is moving towards his goal."Ten     defrunning (self): One         Print "your hero is running to the target." A     defSkills (self): -         Print "your hero is releasing his skills." -     defAttack (self): the         Print "your hero is attacking."

    The above hero base class has four properties for attack, defense, life and Mana, and four ways to walk, run, unleash, and attack.

    Now that you have created a role in front of the computer, Galen, the program begins to instantiate the class:

    1 garen = Hero ()

    OK, your hero character has been generated, let's see what Galen now has (the first four is the attribute, the next four is the method, the middle we first ignore it):

    1 Printdir (garen)2 3C:\Python27\python.exe d:/python/s11/8day/Reflex/test.py4 5['ATK','DEF','HP','MP','__doc__','__init__','__module__','Attack','Running','Skills','Walk']

    And look at the initial properties (well, HP is higher than MP, it appears to be a melee hero):

    1 Print Garen. __dict__ 2 3 C:\Python27\python.exe d:/python/s11/8day/reflex/test.py45 {'HP  'ATK'DEF '  MP': 100}

    Now that the character has been generated, then of course it's time to start working on it. You use the mouse to point to the map, a walk string to the background program, now let's see how the program is handled:

    1 if hasattr (Garen,"walk"):       #传入walk字符串, use the Hasattr function to determine if the role has this method  2     walk = GetAttr (Garen,"walk")    #  If any, use the GetAttr function to remove the method body, but do not execute                         the method with 3 walk () #最后

    Then your character will act accordingly:

    1 C:\Python27\python.exe d:/python/s11/8day/reflex/test.py23 your hero is moving towards the target.


    The release skill is also the same, when you press the Skill shortcut key in the keyboard to send the corresponding skill name to the program, the program converts the name of the skill into an executable verb to execute the corresponding method. The reflection is that the string argument you pass to the object is executed as a method of the same name in the object, provided that the object has this method.
    Of course, reflection is not only object-specific, other extensions to classes, modules, functions and other containers can also use reflection, the following is the reflection of the four methods:

    1     hasattr (): Determines whether a container has the contents of the parameter as its name, if any, according to the input parameters, or True2    getattr (): Takes out the contents of the container in the name of the parameter 3     setattr (): Modify the contents of the container with a parameter name 4     delattr (): Delete the contents of the container with the parameter name

    General back two less use, understand can

  4. Assertion
    Assertion is a more interesting thing, it wants a condition to judge the same, only when satisfied will let the program go down, or error. can be used to detect whether the system environment satisfies the needs of the program, generally used in testing or debugging
    1 assert " mac "    # The program can only be executed on the Mac, and if not, the program is not allowed to execute

  5. Single-Case mode

    is a class, only instantiated once, only a piece of memory, the program would like to use this function when you do not have to instantiate an object, instead of invoking the same instance, shared memory.
    Example: The program will have a special connection to the database class, when the user queries the database will be instantiated once, to create a connection for the object, if the concurrency is very wasteful memory resources, the use of singleton instances only need to instantiate once, then we share a connection instance, this can save a lot of resources.

    Create a singleton pattern class:

    11classFoo (object):22__instance= None#_instance is set to none, indicating that the class has not been instantiated3344 @staticmethod#set as static method55defSingleton ():66ifFoo.__instance:#Determines whether an instance is instantiated, if the __instance is present, instead of creating the instance, it returns the instance created the first time.77returnFoo.__instance88Else:                   99 Foo.__instance= Foo ()#if it has not yet been instantiated, bind the instantiated object instance to __instance and return the instanceTen10returnFoo.__instance

    Create a singleton Schema object:

    1 obj = Foo.singleton ()

  

python--anomaly and reflection in object-oriented discourse

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.