Other related
One, isinstance (obj, CLS)
Checks if obj is an object of class CLS
| 123456 |
classFoo(object): passobj =Foo()isinstance(obj, Foo) |
Second, Issubclass (sub, super)
Check if the sub class is a derived class of super class
| 1234567 |
classFoo(object): passclassBar(Foo): passissubclass(Bar, Foo) |
Third, exception handling
1. Abnormal Foundation
In the programming process in order to increase the friendliness of the program in the event of a bug will not be displayed to the user error message, but the reality of a hint of the page, popular is not to let users see the big Yellow Pages!!!
| 1234 |
try: passexceptException,ex: pass |
Requirement: Add two numbers entered by the user
View Code
2. Abnormal type
There are so many exceptions in Python that each exception is dedicated to handling an exception!!!
Common exceptions More Exception instances: indexerror instance: Keyerror valueerror
For the above instance, the exception class can only be used to handle the specified exception condition and cannot be processed if the unspecified exception is not specified.
| 1234567 |
# 未捕获到异常,程序直接报错s1 =‘hello‘try: int(s1)except IndexError,e: printe |
So, write a program that takes into account any exceptions that might occur in a try code block, which you can write:
| 123456789 |
s1 =‘hello‘try: int(s1)except IndexError,e: print eexcept KeyError,e: print eexcept ValueError,e: printe |
Universal exception in Python's exception, there is a universal exception: Exception, he can catch arbitrary exceptions, namely:
| 12345 |
s1 =‘hello‘try: int(s1)except Exception,e: printe |
Next you may ask, since there is this universal exception, the other exception is not can be ignored!
A: Of course not, exceptions for special handling or reminders need to be defined first, and finally defined exception to ensure that the program runs correctly.
| 123456789 |
s1 =‘hello‘try: int(s1)except KeyError,e: print ‘键错误‘except IndexError,e: print ‘索引错误‘except Exception, e: print‘错误‘ |
3, abnormal other structure
| 123456789101112 |
try: # 主代码块 passexceptKeyError,e: # 异常时,执行该块 passelse: # 主代码块执行完,执行该块 passfinally: # 无论异常与否,最终执行该块 pass |
4. Active Trigger exception
| 1234 |
try: raiseException(‘错误了。。。‘)except Exception,e: printe |
5. Custom Exceptions
| 123456789101112 |
class &N Bsp wupeiqiexception (Exception): def __init__ ( self , msg): self . message = msg def __str__ ( self ): return self . Message try : raise wupeiqiexception ( ' My exception ' ) except Wupeiqiexception,e: print e |
6. Assertion
| 12345 |
# assert 条件assert1 == 1assert 1 ==2 |
Iv. Reflection
The reflection functionality in Python is provided by the following four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and four functions for internal execution of objects: Check for a member, get a member, set a member, delete a member.
Class Foo (object): def __init__ (self): self.name = ' Wupeiqi ' def func: return ' func ' obj = # # # # # # # # # # # # # # # # # # # # #setattr (obj, ' age ', setattr) (obj, ' show ', Lambda Num:num + 1) # # # # # # # # # # # # # # # # # # #delattr attr (obj, ' func ')
Detailed analysis:
This should be done when we want to access the members of an object:
| 1234567891011121314 |
classFoo(object): def __init__(self): self.name = ‘alex‘ def func(self): return ‘func‘obj =Foo()# 访问字段obj.name# 执行方法obj.func() |
So that's the problem? A, what is the name and func of the Access object members mentioned above?
Answer: Is the variable nameb, what does obj.xxx mean?
A: obj.xxx means to go to obj or class to find the variable name xxx, and get the corresponding memory address of the content. C, requirements: Please use another way to get the name variable in the Obj object to the value in memory "Alex" asks the way one way two
D, compare three kinds of access methods
- Obj.name
- obj.__dict__[' name ']
- GetAttr (obj, ' name ')
A: The first and the other kinds of ratio, ...
The second and the third ratio, ...
Web Framework Instances
Conclusion: Reflection is a member of an object related to manipulating objects in the form of a string. all things are objects!!!
Reflect current Module members
Class is also an object
| 1234567891011121314151617 |
classFoo(object): staticField ="old boy" def__init__(self): self.name =‘wupeiqi‘ deffunc(self): return‘func‘ @staticmethod defbar(): return‘bar‘printgetattr(Foo, ‘staticField‘)printgetattr(Foo, ‘func‘)printgetattr(Foo, ‘bar‘) |
Modules are also objects
home.py
| 12345678910111213141516171819 |
#!/usr/bin/env python# -*- coding:utf-8 -*-"""程序目录: home.py index.py当前文件: index.py"""importhome as obj#obj.dev()func =getattr(obj, ‘dev‘)func() |
Expand:
Import module (Reflection implementation):
A = __import__ ("Module name")
A = __import__ (' lib.test.com ', fromlist=true)
python--Object-oriented correlation