码迷,mamicode.com
首页 > 编程语言 > 详细

python 反射

时间:2016-01-16 11:54:44      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

python中的反射功能有一下四种函数:hasattr,getatter,setattr,delattr.这四个函数分别用于对对象内部执行

hasattr-查询

getattr-获取

setattr-修改

delattr-删除

 

 1 class Foo(object):
 2     def __init__(self):
 3         self.name = gavin
 4 
 5     def f1(self):
 6         pass
 7 
 8     @classmethod
 9     def f2(cls):
10         ‘‘‘类方法‘‘‘
11         pass
12 
13     @staticmethod
14     def f3(a,b):
15         ‘‘‘自定义静态方法‘‘‘
16         pass
17 
18 obj = Foo()
19 
20 #查看里面的成员
21 print Foo.__dict__.keys()
22 
23 print "查看对象里面的相关成员"
24 print hasattr(obj,f1)
25 print hasattr(Foo,f2)
26 print hasattr(Foo,f3)
27 
28 print "获取对象里面的相关成员"
29 print getattr(obj,f1)
30 print getattr(Foo,f2)
31 print getattr(Foo,f3)
32 
33 print "修改对象里面的相关成员"
34 print setattr(obj,f1,12)
35 
36 print "删除对象里面的相关成员,在内存中删除"
37 print delattr(obj,‘f1‘)
38 print delattr(Foo,f2)
39 print delattr(Foo,f3)
40 print Foo.__dict__.keys()

 

python 反射

标签:

原文地址:http://www.cnblogs.com/guociming/p/5135121.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!