isinstance

class A:
pass
class B(A):
pass

b = B()
print isinatance(b,A)
issubclass 判断某一个类是不是另外一个类的派生类

#################################################################

自定义异常
class demoerror(Exception):

def __str__(self):
return 'this is error'

try:
raise demoerror()
except Exception ,e:
print e、
#################################################################

自定义一个带参数的异常
class demoerror(Exception):
def __init__(self,msg):
self.msg = msg

def __str__(self):
if self.msg:
return self.msg
else:
return 'sesesesesseseseese'
try:
raise demoerror('lalalalalalalalalala')
except Exception ,e:
print e
#################################################################

反射:根据参数的名字 动态的调用方法

【1】getattr ---> 获取某个容器的某个函数
---------index.py
import home
res = 'home'
func = getattr(home,res) # 获取 home模块里面的 home函数
res = func() # 执行并且获取返回值
print res

------------home.py
def home():
print 'home'
return 'ok'

结果:
home
ok
【2】 hasattr -->判断某个容器是不是有某个模块
--------index.py
import home
res = 'home'
rus = 'demo'
func1 = hasattr(home,res)
func2 = hasattr(home,rus)
print func1,func2

------------home.py
def home():
print 'home'
return 'ok'
结果:
True False
------------------------------------------------------------
模拟web框架中的使用
-------------webdemo.py

from wsgiref.simple_server import make_server
def RunServer(environ,start_response):
start_response('200 OK',[('Content-Type','text/html')])
url = environ['PATH_INFO']
temp = url.split('/')[1]
import home

is_exist = hasattr(home.temp)
#home模块中检查有没有跟穿过来url名称一样的方法

if is_exist:
func = getattr(home,temp)
ret = func()
return ret
else:
return '404 not found'

if __name__ == '__main__':
httpd = make_server('',8001,RunServer)
print "SERVER in 8001"
httpd.serve_forever()
----home.py
xxxx
xxxx
xxxx

其他应用
setattr:给某个容器设置一个方法
----index.py
import home
res = 'lala'
func = setattr(home,res,'hello world')
fures = getattr(home,res)
print fures

输出:
hello world

在内存中给home这个空间 设置设置一个方法 res
-----------------------------------
delattr:删除某个函数的方法
import home
res = 'lala'
func = setattr(home,res,'hello world')
#res = getattr(home,res)
#print res
func1 = delattr(home,res)
res1 = hasattr(home,res)
print res1

#################################################################

反射操作类的成员

__author__ = 'Administrator'
class Leo:
start_name = 'rico' def __init__(self):
self.start_name = 'NEO'
def show(self):
print 'show me' @staticmethod
def start_show():
print 'start_show'
@classmethod
def class_show(cls):
print 'class_show' print Leo.__dict__.keys() print hasattr(Leo,'show')
=======================================================
反射导入多层模块
--index.py
__author__ = 'Administrator'
import home cls = getattr(home,'Leo')
print cls
s_name = getattr(cls,"start_name")
print s_name
--home.py
class Leo:
start_name = 'rico' def __init__(self):
self.start_name = 'NEO'
def show(self):
print 'show me'
输出:

home.Leo
rico

----------------

--index.py

__author__ = 'Administrator'
import home cls = getattr(home,'Leo')
obj =cls()
name = getattr(obj,"start_name")
print name
输出:
NEO 前者是类的静态字段 后者是调用类里的方法的静态字段
cls()代表实例化这个类

===========================================

动态导入模块

----home.py

__author__ = 'Administrator'
def index():
print 'index'
return 'return' def home():
pass

---index.py
con,action = raw_input('url:').split('/')
module = __import__(con)
func= getattr(module,action)
ret = func()
print ret

输入输出:

url:home/index #输入
index   --输出
return --输出

==========================================================

												

python基础补漏-09-反射的更多相关文章

  1. Python基础2:反射、装饰器、JSON,接口

    一.反射 最近接触到python的反射机制,遂记录下来已巩固.但是,笔者也是粗略的使用了__import__, getattr()函数而已.目前,笔者的理解是,反射可以使用户通过自定义输入来导入响应的 ...

  2. python基础-类的反射

    1)反射是通过字符串方式映射内存中的对象. python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr, 改四个函数分别用于对对象内部执行:检查是 ...

  3. python基础学习笔记——反射

    对编程语言比较熟悉的朋友,应该知道“反射”这个机制.Python作为一门动态语言,当然不会缺少这一重要功能.然而,在网络上却很少见到有详细或者深刻的剖析论文.下面结合一个web路由的实例来阐述pyth ...

  4. python基础-面向对象编程之反射

    面向对象编程之反射 反射 定义:通过字符串对对象的属性和方法进行操作. 反射有4个方法,都是python内置的,分别是: hasattr(obj,name:str) 通过"字符串" ...

  5. python基础补漏-06-其他常用模块

    JSON/Pickle: 首先我们要明白 什么事序列化--> 就是进行不同程序之间的数据交换 那JSON 和Pickle是什么鬼... 就是不同的方式而已 import json name = ...

  6. python基础补漏-06-内置模块

    1> sys 模块 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序的 ...

  7. python基础补漏-04-常用函数

    ----lambda 首先我们说,很遗憾 在python中lambda 仅仅只是一个表达式 那么如何去使用呢? 这个是lambda最简单的使用方式  一般跟map一起配合使用 --map (fun,l ...

  8. python基础补漏-03-函数

    函数:一般来说就是 以功能划分的代码模块 [1] 内置函数 一般我们使用的模块 ---可以大概有个了解 大多数的用法都很简单 2 [函数返回值] 我们应该控制函数的每条分支. 也就是说 我们得到的函数 ...

  9. python基础补漏-02-collection

    collection系列 [1]计数器 Counter import collections res = collections.Counter("34234sdfgs45tsaf1&quo ...

  10. python基础补漏-01

    python对象的方法 1.python的特性:一切皆对象 2 type(obj) 查看对象的类型 3 dir(obj)查看类中所有详细的功能 4 help(obj) 查看类中所有详细的功能 类中的方 ...

随机推荐

  1. ajax在购物车中的应用

    代码如下: 购物车页面: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: ...

  2. 【虚拟机-部署】通过 Powershell 来调整 ARM 模式下虚拟机的尺寸

    需求描述 在部署完 ARM 模式的虚拟机以后,可以通过 PowerShell 命令来调整虚拟机的尺寸,以下是通过 PowerShell 命令来调整 ARM 模式的虚拟机尺寸. Note 本文只限于 A ...

  3. Exchange 用户邮箱导入/导出

    在第2部分中,我将向您介绍如何使用Exchange Server中提供的新cmdlet导入/导出数据,以及如何查看导入和导出的信息统计信息这样做. 走起! 将数据从PST文件导入到邮箱 现在是时候尝试 ...

  4. [uva816]AbbottsRevenge Abbott的复仇(经典迷宫BFS)

    这题思路就普通的BFS加上一个维度朝向,主要是要注意输入,输出,以及细节的处理 #include<cstdio> #include<cstring> #include<q ...

  5. Cross-Entropy Loss 与Accuracy的数值关系(很重要,很好的博客)

    http://www.cnblogs.com/dengdan890730/p/6132937.html

  6. no pointer in java

    Why there are no pointers in Java? In Java there are references instead of pointers. These reference ...

  7. How to restrict root user to access or modify a file and directory in Linux

    Now in this article I will show you steps to prevent or restrict access of root user to access certa ...

  8. spring5之SAXParseException:cvc-elt.1: 找不到元素 “beans” 的声明

    之前SSM项目一直报错,就是找不到错误  气啊 后来在网上找到了答案:燕来spring5之后就不再需要写版本号了

  9. springmvc的第一个程序

    文中用的框架版本:spring 3,hibernate 3,没有的,自己上网下. web.xml配置: <?xml version="1.0" encoding=" ...

  10. 服务器上搭建flowvisor平台

    之前全是在virtualbox上的Ubuntu虚拟机上测试的ovs以及pox, 现在我们开始在服务器上开始了 两台服务器上的ovs均是1.4.6版本 遇到一个问题:之前装的ovs down了 然后什么 ...