python基础补漏-09-反射
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-反射的更多相关文章
- Python基础2:反射、装饰器、JSON,接口
一.反射 最近接触到python的反射机制,遂记录下来已巩固.但是,笔者也是粗略的使用了__import__, getattr()函数而已.目前,笔者的理解是,反射可以使用户通过自定义输入来导入响应的 ...
- python基础-类的反射
1)反射是通过字符串方式映射内存中的对象. python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr, 改四个函数分别用于对对象内部执行:检查是 ...
- python基础学习笔记——反射
对编程语言比较熟悉的朋友,应该知道“反射”这个机制.Python作为一门动态语言,当然不会缺少这一重要功能.然而,在网络上却很少见到有详细或者深刻的剖析论文.下面结合一个web路由的实例来阐述pyth ...
- python基础-面向对象编程之反射
面向对象编程之反射 反射 定义:通过字符串对对象的属性和方法进行操作. 反射有4个方法,都是python内置的,分别是: hasattr(obj,name:str) 通过"字符串" ...
- python基础补漏-06-其他常用模块
JSON/Pickle: 首先我们要明白 什么事序列化--> 就是进行不同程序之间的数据交换 那JSON 和Pickle是什么鬼... 就是不同的方式而已 import json name = ...
- python基础补漏-06-内置模块
1> sys 模块 sys.argv 命令行参数List,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit(0) sys.version 获取Python解释程序的 ...
- python基础补漏-04-常用函数
----lambda 首先我们说,很遗憾 在python中lambda 仅仅只是一个表达式 那么如何去使用呢? 这个是lambda最简单的使用方式 一般跟map一起配合使用 --map (fun,l ...
- python基础补漏-03-函数
函数:一般来说就是 以功能划分的代码模块 [1] 内置函数 一般我们使用的模块 ---可以大概有个了解 大多数的用法都很简单 2 [函数返回值] 我们应该控制函数的每条分支. 也就是说 我们得到的函数 ...
- python基础补漏-02-collection
collection系列 [1]计数器 Counter import collections res = collections.Counter("34234sdfgs45tsaf1&quo ...
- python基础补漏-01
python对象的方法 1.python的特性:一切皆对象 2 type(obj) 查看对象的类型 3 dir(obj)查看类中所有详细的功能 4 help(obj) 查看类中所有详细的功能 类中的方 ...
随机推荐
- svn与git区别简介,git分支操作在mac客户端soureTree和使用命令行如何实现
svn与git区别简介: 性能方面(经过实践的) svn:下载速度慢,因为它其中的源文件太多,并且在show log日志的时候每次都需要去服务器拉取,速度很慢 git:下载速度快,并且git clon ...
- windows server 2008 r2 启用 Windows Defender
单击“开始”,指向“管理工具”,然后单击“服务器管理器”. 在“服务器管理器”中,单击“功能”,然后在“服务器管理器”细节窗格中的“功能摘要”下,单击“添加功能”. 此时会启动“添加功能向导”. 在“ ...
- JDBC + SAP云平台 = 运行在云端的数据库应用
在前一篇文章JPA + EclipseLink + SAP云平台 = 运行在云端的数据库应用我介绍了如何通过JPA和EclipseLink操作部署在SAP云平台上的HANA数据库实例. 在这篇文章里, ...
- mvc的help和functions语法
@helper show(int num ) { ) { @:存在 } else { @:不存在 } } @functions { /// <summary> /// 方法必须要求为静态 ...
- cv2.Laplacian 模糊判断
简介 cv2.Laplacian是用来判断图像模糊度的 函数原型 dst = cv2.Laplacian(src, ddepth[, dst[, ksize[, scale[, delta ...
- 使用ErrorProvider组件验证文本框输入
实现效果: 知识运用: ErrorProvider组件的BlinkStyle属性 //指示错误图标的闪烁时间 public ErrorBlinkStyle BlinkStyle{ get;set; } ...
- Python列表解析与生成器表达式
Python列表解析 l = ["egg%s" %i for i in range(100) if i > 50] print(l) l= [1,2,3,4] s = 'he ...
- 课外作业1:将一个double类型的小数,按照四舍五入保留两位小数
package come.one01; public class One02 { public static void main(String[] args) { double numa = 3.14 ...
- vim 自动补全 颜色设置
vim 自动补全 颜色设置 hi Pmenu ctermfg=black ctermbg=gray guibg=# hi PmenuSel ctermfg= ctermbg= guibg=# guif ...
- 使用lua做序列化和反序列化
-- lua对象序列化 function serialize(obj) local lua = "" local t = type(obj) if t == "numbe ...