Home IT Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Python-- for anomalies and reflection of objects articles     - Linux configuration Samba server (Server)

- Impact test noatime Linux file access time (Linux)

- Linux system firewall defense network attacks (Linux)

- MySQL5.6.17 compiler installation under CentOS (Database)

- C ++ sequence containers basics summary (Programming)

- Large site architecture study notes (Server)

- Linux system security configuration (Linux)

- Android SDK Manager can not update the domestic solutions (Linux)

- MongoDB upgrade to 2.6 (Database)

- Storm basic framework for analysis (Programming)

- Definition Format Oracle basis of various statements (Database)

- C ++ string in the end (Programming)

- Linux command binlog by filtering out the complete SQL statement (Database)

- Lsblk command lists using Linux block device information (Linux)

- Use the dd command to the hard disk I / O performance test (Linux)

- Linux command -nohup & (Linux)

- C ++ function object (Programming)

- Syncthing: Private Security Synchronization tool to synchronize files between computers / folder (Linux)

- Source install Python3.4 on CentOS (Linux)

- SSH mutual trust configuration (Server)

  Python-- for anomalies and reflection of objects articles
  Add Date : 2018-11-21      
  Python-- for anomalies and reflection of objects articles

1. built-in functions and issubclass isinstance

1.1 isinstance Usage:

isinstance (string, str)

The first parameter to judge whether the second argument is a subset, for example:

print isinstance ( "test", str) # determine whether the test is a string type

C: Python27 python.exe D: / python / s11 / 8day / reflection /test.py


print isinstance (123, int) # 123 judges whether the integer type

C: Python27 python.exe D: / python / s11 / 8day / reflection /test.py


 You can also determine whether an object is an instance of a class, returns a Boolean value

1.2 issubclass Usage:

 issubclass (sub, super)
  Determine whether the super sub derived class, the return value is a Boolean value

NOTE: Use isinstance and issubclass will destroy the object polymorphism

Exception Handling
     python after it encounters an error, it will throw an exception if the exception object has not been handled or captured, the presentation will use a so-called back (traceback) to terminate the execution of the program, as follows:

C: Python27 python.exe D: / python / s11 / 8day / reflection /test.py
Traceback (most recent call last):
File "D: /python/s11/8day/test.py", line 26, in
print isinstance (d, int)
NameError: name 'd' is not defined

      In python, the exceptions are instances of each class of Exception, Exception can say is the base class for all exceptions. If we catch the error and its treatment, and that the whole process will not be back but to continue execution.

 2.1 Passive exception
            That write the code in the try block, when the program throwing error triggered automatically, except is responsible for capturing and handling exceptions, are used as follows

      Code block
 except Exception, e: #e exception is an instance of an object; the above error message is encapsulated in the e exception handling # Here you can print exception information, such as (print e); you can also do other operations, such as the exception information into the log

      In this Note: If you print e time, because it is the normal print objects should be returned when the memory address of the object, and in exception handling here, you print object calls exception of __str__ method, the exception information is returned instead of returning the memory address, so here you will find time to print show will be exceptions, which you do not feel strange.

       Except when an exception is caught, you can plus months except in the back except, like water filtration as a layer of Catching specific

     Code block
 except KeyError, e: # trying to access a non-existent dictionary key
     print e
 except ValueError, e: # incoming caller does not expect a value type even if the value is correct
    print e
 except Exception, e: # If you can not expect anything unusual will happen, well, we have a universal exception
     print e
         Another way:

     Garen = Hero
 except (KeyError, ValueError), e: # tuples written form
     print e

2.2 Active trigger abnormal
           Ranging program code encounters an error is thrown after the trigger, but we are expected to advance to trigger local problems

     raise Exception ( 'error here') # ahead of the Senate and instantiate Exception
 except Exception, e: # wrong message encapsulated exception of instances where e
     print e

2.3 custom exception
           Both our own definition of trigger conditions and treatment of abnormal, create a custom exception when the need for direct or indirect inheritance Exception

 class testError (exception): // inherit the base class exception exception
     def __init __ (self, msg = None):
         self.msg = msg
     def __str __ (self):
         if self.msg: // dynamically according to the parameters passed to display exception information
             return self.msg
             return "custom exception" // default display abnormal information

Call custom exception

     raise testError () // instantiate a custom exception class, parameters can be passed back brackets
 except testError, e:
     print e

2.4 finally
           Regardless of whether an exception occurs try clause is executed, such as when you read and write files or scoket communicate, regardless of whether an exception should be closed at the end of a file or network socket, then we can finally put a close method on the child sentence

     f = open ( "test.txt", "a")
     f.write (data)
 except Exception, e:
     print e
     f.close ()

2.5 ignores all exceptions
     Garen = Hero

     This is a relatively dangerous to use, it will ignore all exceptions allow the program to continue the program execution down.
Exception handling only need to remember one thing: when we know that a piece of code may cause some abnormality, but we do not want the program to stop, then we can add exception handling as needed.

Extension: internal reflections getattr implementation AttributeError abnormal area is captured by accessing properties and can lead to the realization of

Reflection, will be converted into a verb name, which is the author reading "Execution in the Kingdom of Nouns" After the first reaction reflected, we are interested can go to read, an article not too long.

      Let's imagine such a scenario: you sat at the computer, playing LOL, transmission of information via mouse and keyboard, the hero of the game to make the corresponding operation, which can be seen as reflections. This is how to do it? Let's look down:

First we define a hero template, which is the base class.
 class Hero:
     def __init __ (self):
         self.ATK = 30
         self.DEF = 10
         self.HP = 300
         self.MP = 100
     def walk (self):
         print "Your hero is moving toward the goal."
     def running (self):
         print "Your goal is dashing hero"
     def skills (self):
         print "your hero skills being released."
     def attack (self):
         print "your hero is attacking."
 Above this base class hero attack, defense, life and mana four properties as well as walking, running, release skills and attack four methodological acts.

 Now you're in front of the computer to create a role Galen, the program starts the class is instantiated:

 Garen = Hero ()

 OK, your hero character has been generated, let us look at what has now Galen (front four is an attribute, followed by four is a method, whether it be among us):

 print dir (Garen)
 C: Python27 python.exe D: / python / s11 / 8day / reflection /test.py
 [ 'ATK', 'DEF', 'HP', 'MP', '__doc__', '__init__', '__module__', 'attack', 'running', 'skills', 'walk']
 Look at how much the initial property is (TU, HP higher than the MP, it seems melee hero):

 print Garen .__ dict__
 C: Python27 python.exe D: / python / s11 / 8day / reflection /test.py
 { 'HP': 300, 'ATK': 30, 'DEF': 10, 'MP': 100}
 Since the role of generating, next, of course, to begin to operate. You point with the mouse on the map for a moment, a walk in the string passed to the daemon, now let's look at how the program is addressed:

 if hasattr (Garen, "walk"): # Incoming walk strings, use hasattr function to determine whether the role of this method
     walk = getattr (Garen, "walk") # if you use getattr function removed the body of the method, but does not perform
     walk () # Finally the method is performed
Then your character will do the appropriate action:

 C: Python27 python.exe D: / python / s11 / 8day / reflection /test.py
 Your hero is moving toward the goal

      Release skills, too, when you press the keyboard shortcut key skills in the corresponding skill name issue, program the skill name into a verb executable corresponding method is executed. That white is the reflection of the object you pass the string parameter as an object of the same name to perform the method, provided that the object with this method.
      Of course, not just objects reflection proprietary, extended to other classes, modules, functions, and so the container can also use reflection, here are four methods of reflection:

     hasattr (): according to the input parameters to judge whether there has been a container for the content of the parameter name, if it returns true
     getattr (): Remove the container with the name of the parameter content
     setattr (): the container to the name of the parameter content modifications
     delattr (): Remove the container to the name of the parameter content
      Usually the latter two rarely used, you can understand

     Assertion is a more interesting thing, it wanted to judgment as a condition, if only to meet the program will go on, otherwise an error. It can be used to detect whether the system environment to meet the needs of the program, usually at the time of testing or debugging
 assert system == "mac" # programs can only be executed on the mac, if not satisfied with the implementation of a program to prevent
Singleton Pattern
     Both a class is instantiated only once, occupies only a memory, each program would like to use this function when it no longer instantiate an object, it calls the same instance, shared memory.
     Example: The program will have a special connection class database when users query the database will be instantiated once, create an object for the connection, if concurrent large would be very wasteful of memory resources using a single instance of, then you only need to instantiate a after we share a connection instance, this can save a lot of resources.

Singleton class is created:

 class Foo (object):
     __instance = None #_instance set to None, this class has not been instantiated
     @staticmethod # Set the static method
    def singleton ():
         if Foo .__ instance: # determine whether instantiated before, no longer exist if __instance create an instance, but directly returns an instance is created the first time
             return Foo .__ instance
             Foo .__ instance = Foo () # if it has not been instantiated, it instantiates an object instance is bound to __instance, and returns this instance
             return Foo .__ instance

Singleton objects created:

 obj = Foo.singleton ()
- Based on Python: OpenCV simple image manipulation (Programming)
- Python several standard types of built-in functions (Programming)
- Analysis of Java in the deep copy and shallow copy (Programming)
- Make Windows boot disk to install USB in Ubuntu Linux (Linux)
- pscp use Detailed Windows and Linux each file transfer tool (Linux)
- Shell Programming Regular Expressions (Programming)
- Linux check disk parameters trapping lack amendments (Linux)
- Linux system network security tools sudo Introduction (Linux)
- CentOS7 iptables (Linux)
- Experience RHEL7 new features (Linux)
- Oracle archive log summary (Database)
- Let the terminal under Mac OS X as like Linux has displayed a variety of colors (Linux)
- Online booking shocking information leakage risk, you dare book the tickets online? (Linux)
- Analyzing Linux server architecture is 32-bit / 64-bit (Server)
- NIC configuration parameters under Linux (Linux)
- Ubuntu and derivatives installation Atom 0.104.0 (Linux)
- Why learn and use C language (Programming)
- Vagrant Getting Start (Linux)
- 10 useful Linux command Interview Questions and Answers (Linux)
- GCC library link order problems (Programming)
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.