Python 3.x study note 12 (reflection and exception), python3.x
1. Reflection
Use string ing or modify the status, attributes, and methods when the program is running
Getattr (obj, name_str): obtains the memory address of the corresponding method in the obj object based on the string name_str.
Hasttr (obj, name_str): method used to determine whether a corresponding string exists in an object obj
Setattr (obj, 'y', z): The getatt () function corresponding to the setattr function is used to set the attribute value. This attribute must exist.
Delattr (obj, 'y'): deletes named attributes from a given object.
Class Dog (object): def _ init _ (self, name): self. name = name def eat (self): print ('% s is eating .... '% self. name) d = Dog ('xiaohei') # instantiate the choice = input ('>>>>:') object :'). strip () # strip () Remove left and right spaces if hasattr (d, choice): # Check if choice func = getattr (d, choice) is present in instantiation d) # getattr returns the choice memory address func () in d # execute the Function
2. Exception Basics
In the programming process, in order to increase friendliness, when a program encounters a bug, the error information is generally not displayed to the user, but rather a prompt page. In other words, the user is not allowed to see the yellow pages.
1) Basic Structure
try: passexcept Exception as e: pass
2) Other Structures
# Exception structure try: # main code block passexcept KeyError as e: # When an exception occurs, execute this block passelse: # after the main code block is executed, that is, no exception occurs. Execute this block passfinally: # This block pass is executed no matter whether an exception occurs or not.
3)Actively trigger exceptions
Try: raise Exception ('error... ') failed t Exception as e: print (e)
3. Common exception types
AttributeError # try to access a tree without an object, such as foo. x, but foo has no attribute x
IOError # input/output exceptions. Basically, files cannot be opened.
ImportError # The module or package cannot be introduced. It is basically a path problem or a name error.
IndentationError # syntax error (subclass of); the Code is not correctly aligned
IndexError # The subscript index exceeds the sequence boundary. For example, if x has only three elements, it tries to access x [5].
KeyError # try to access a key that does not exist in the dictionary
KeyboardInterrupt # Ctrl + C is pressed
NameError # use a variable that has not been assigned an object
SyntaxError # The Python code is invalid and cannot be compiled. (I think this is a syntax error and it is wrong)
TypeError # the type of the input object does not meet the requirements
UnboundLocalError # try to access a local variable that has not been set, basically because there is another global variable with the same name, you think you are accessing it
ValueError # pass in a value that the caller does not expect, even if the value type is correct