python的对象反射功能,经常在编程时使用.相比较其它的编程语言使用非常方便.反射就是用字符串来操作对象或者类,模块中的成员.

一.对象的反射

反射功能的实现,由这4个内置函数来实现(hasattr, getattr, setattr, delattr)

1.1.hasattr判断是否有某个成员

判断对象中是否有属性, 方法.返回bool值

#!/usr/bin/env python
# -*-coding:utf-8-*-

class Foo(object):
country = "china"

def __init__(self, name):
self.name = name

def f(self):
print "function f"

obj = Foo("abc")
print hasattr(obj, "name") #判断是否有name字段,返回True
print hasattr(obj, "f") #判断是否有f方法,返回True
print hasattr(obj, "ok") #没有这个方法,返回False
print hasattr(obj, "country") #判断有没有静态字段,返回True
print hasattr(Foo, "country") #使用类作为参数来判断
print "class:", Foo.__dict__.keys()
print "obj:", obj.__dict__.keys()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "function f"
 
obj = Foo("abc")
print hasattr(obj, "name")         #判断是否有name字段,返回True
print hasattr(obj, "f")            #判断是否有f方法,返回True
print hasattr(obj, "ok")           #没有这个方法,返回False
print hasattr(obj, "country")      #判断有没有静态字段,返回True
print hasattr(Foo, "country")      #使用类作为参数来判断
print "class:", Foo.__dict__.keys()
print "obj:", obj.__dict__.keys()

上例中使用对象作为obj参数来判断,是否有类的静态方法.也是可以的.因为对象的特殊性,先在对象中找是否有该成员,如果没在,通过对象指针,在去创建这个对象的类中找查

执行结果

True
True
False
True
True
class: ['__module__', 'f', 'country', '__dict__', '__weakref__', '__doc__', '__init__']
obj: ['name']
1
2
3
4
5
6
7
True
True
False
True
True
class: ['__module__', 'f', 'country', '__dict__', '__weakref__', '__doc__', '__init__']
obj: ['name']

1.2.获取对象的成员

也可以使用对象来获取类的成员.和上例中的hasattr一样

#!/usr/bin/env python
# -*-coding:utf-8-*-

class Foo(object):
country = "china"

def __init__(self, name):
self.name = name

def f(self):
print "this is function = ", self.name
obj = Foo("abc")
print getattr(obj, "name") #获取对象的name字段
f = getattr(obj, "f") #通过对象获取类的方法
print f #打印出来是信类的方法
f() #加上括号就能直接调用执行这个的方法
print getattr(Foo, "country")
print getattr(obj, "country") #使用对象也能找到静态字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "this is function = ", self.name
obj = Foo("abc")
print getattr(obj, "name")             #获取对象的name字段
f = getattr(obj, "f")                  #通过对象获取类的方法
print f                                #打印出来是信类的方法
f()                                    #加上括号就能直接调用执行这个的方法
print getattr(Foo, "country")
print getattr(obj, "country")          #使用对象也能找到静态字段

1.3.增加对象或者类的成员

动态的增加对象或者类中的成员

#!/usr/bin/env python
# -*-coding:utf-8-*-

class Foo(object):
country = "china"

def __init__(self, name):
self.name = name

def f(self):
print "this is function f.name = ", self.name

obj = Foo("abc")
setattr(obj, "age", 19) #增加普通字段
setattr(obj, "show", lambda num: num +1) #增加普通方法
setattr(Foo, "tel", "+086") #增加静态字段
print obj.age
print Foo.tel
print obj.show(10)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "this is function f.name = ", self.name
 
 
obj = Foo("abc")
setattr(obj, "age", 19)                       #增加普通字段
setattr(obj, "show", lambda num: num +1)      #增加普通方法
setattr(Foo, "tel", "+086")                   #增加静态字段
print obj.age
print Foo.tel
print obj.show(10)

执行结果

19
+086
11
1
2
3
19
+086
11

1.4.使用delattr动态的删除类或者方法成员

演示代码

#!/usr/bin/env python
# -*-coding:utf-8-*-

class Foo(object):
country = "china"

def __init__(self, name):
self.name = name

def f(self):
print "this is function f.name = ", self.name

obj = Foo("abc")
print getattr(obj, "name")
delattr(obj, "name") #删除掉了对象的普通字段name
print getattr(obj, "name")
print getattr(Foo, "country")
delattr(Foo, "country") #删除掉类的静态字段
print getattr(Foo, "country") #打印时说找不到些成员,报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
class Foo(object):
    country = "china"
 
    def __init__(self, name):
        self.name = name
 
    def f(self):
        print "this is function f.name = ", self.name
 
 
obj = Foo("abc")
print getattr(obj, "name")
delattr(obj, "name")                     #删除掉了对象的普通字段name
print getattr(obj, "name")
print getattr(Foo, "country")
delattr(Foo, "country")                  #删除掉类的静态字段
print getattr(Foo, "country")            #打印时说找不到些成员,报错

执行结果

Traceback (most recent call last):
File "D:/����/python/��������/day08/blog/fanshe.py", line 17, in <module>
abc
print getattr(obj, "name")
AttributeError: 'Foo' object has no attribute 'name'
1
2
3
4
5
Traceback (most recent call last):
File "D:/����/python/��������/day08/blog/fanshe.py", line 17, in <module>
abc
print getattr(obj, "name")
AttributeError: 'Foo' object has no attribute 'name'

二.在当前模块中使用反射

获取到对应的模块.

#!/usr/bin/env python
# -*-coding:utf-8-*-

import sys

data = "abc"
def f1():
print "f1 function"
def f2():
print "f2"

this_module = sys.modules[__name__]
print hasattr(this_module, "data") #使用反射
f1_get = getattr(this_module, "f1") #使用反射获取
f1_get()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
# -*-coding:utf-8-*-
 
import sys
 
data = "abc"
def f1():
    print "f1 function"
def f2():
    print "f2"
 
this_module =  sys.modules[__name__]
print hasattr(this_module, "data")             #使用反射
f1_get = getattr(this_module, "f1")            #使用反射获取
f1_get()

以上是反射对类,对象,模块成员操作的基本方法.

三.使用字符串自动导入模块

依据传入的字符串,自动导入模块.类似上文的方法反射

import importlib

my_moudle_name = "lib.aa"
aa = importlib.import_module(my_moudle_name)

print(aa)
print(aa.C().name)

1
2
3
4
5
6
7
import importlib
 
my_moudle_name = "lib.aa"
aa = importlib.import_module(my_moudle_name)
 
print(aa)
print(aa.C().name)

执行结果

<module 'lib.aa' from 'D:\\python\\day10\\lib\\aa.py'>
ait24
1
2
<module 'lib.aa' from 'D:\\python\\day10\\lib\\aa.py'>
ait24

python对象反射和函数反射的更多相关文章

  1. python记录_day18 反射 判断函数与方法

    一.三个内置函数 1.issubclass(a, b)  判断a类是否是b类的子类 class Foo: pass class Zi(Foo): pass class Sun(Zi): pass pr ...

  2. Python面试题之Python对象反射、类反射、模块反射

    python面向对象中的反射:通过字符串的形式操作对象相关的属性.python中的一切事物都是对象(都可以使用反射) 一.getattr 对象获取 class Manager: role = &quo ...

  3. python开发面向对象进阶:反射&内置函数

    isinstance和issubclass isinstance(obj,cls)检查是否obj是否是类 cls 的对象或者子类的对象 class Foo(object): pass class ba ...

  4. Python - 面对对象(其他相关,异常处理,反射,单例模式,等..)

    目录 Python - 面对对象(其他相关,异常处理,反射,等..) 一.isinstance(obj, cls) 二.issubclass(sub, super) 三.异常处理 1. 异常处理 2. ...

  5. Python学习日记(二十七) 反射和几个内置函数

    isinstance() 判断isinstance(obj,cls)中obj是否是cls类的对象 class Person: def __init__(self,name): self.name = ...

  6. Python面向对象06 /元类type、反射、函数与类的区别、特殊的双下方法

    Python面向对象06 /元类type.反射.函数与类的区别.特殊的双下方法 目录 Python面向对象06 /元类type.反射.函数与类的区别.特殊的双下方法 1. 元类type 2. 反射 3 ...

  7. python 面向对象专题(六):元类type、反射、函数与类的区别、特殊的双下方法

    目录 Python面向对象06 /元类type.反射.函数与类的区别.特殊的双下方法 1. 元类type 2. 反射 3. 函数与类的区别 4. 特殊的双下方法 1. 元类type type:获取对象 ...

  8. python基础之 面向对象之反射

    1.isinstance和issubclass issubclass(Son,Foo) 判断雷与类之间的是否有继承关系,接受两个参数,一个是疑似子类,一个是疑似父类,判断Son是否是Foo的子类 ob ...

  9. 百万年薪python之路 -- 面向对象之 反射,双下方法

    面向对象之 反射,双下方法 1. 反射 计算机科学领域主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省) python面向对象中的反射:通过字符串的形式操作对象相关的属性.python ...

随机推荐

  1. 关于PHP中的 serialize () 和 unserialize () 的使用(即关于PHP中的值与已存储的表示的相互转换)

    有时,我们会碰到这样的数据(字符串) 1 a:3:{i:0;s:44:"/Uploads/images/2017-07-21/5971a9a08ad57.png";i:1;s:44 ...

  2. 一些有用的java 框架

    jwt  用于生成web toke的类库 http://jwt.io/ jasypt java加密类库 http://www.jasypt.org/

  3. 修改JS文件不能及时在页面中体现,需重启浏览器?

    对JS文件做个小小的改动,哪怕是加一句简单的ALERT语句,都要重启浏览器才能看到.你有这样的烦恼吗?怎样不用重启浏览器就能及时体现JS的变化呢? 对浏览器(IE)做如下设置即可:1.点击 工具栏 - ...

  4. 4606: [Apio2008]DNA

    4606: [Apio2008]DNA Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 63  Solved: 36[Submit][Status][D ...

  5. Castle DynamicProxy creation出现COMException(0x800703fa)错误的解决方案

    昨天有客户反馈周末重启服务器后,几台服务器上的应用运行全部出错.大致错误内容如下: COMException(0x800703fa):试图在标记为删除的注册表项上进行不合法的操作. 通过查看异常堆栈, ...

  6. CentOS上传下载查看命令

    之前往CentOS中上传都用ftp软件,这里介绍一种另外的上传下载方式,两个命令轻松搞定.这两个命令目前只针对Xshell和SecureCRT等远程终端软件才支持,并且还会有时间的限制.大概30秒不上 ...

  7. 【BZOJ3328】PYXFIB 数论+矩阵乘法

    [BZOJ3328]PYXFIB Description Input 第一行一个正整数,表示数据组数据 ,接下来T行每行三个正整数N,K,P Output T行,每行输出一个整数,表示结果 Sampl ...

  8. Unity3D笔记十八 GL图像库

    1.绘制2D图像的时需要使用GL.LoadOrtho()方法来将图形映射到平面中. 2.所有绘制相关的内容都要写在OnPostRender()方法中. 3.有关GL图像库的脚本需要绑定到Hierarc ...

  9. 思科SVI接口和路由接口区别

    Cisco多层交换中提到了一个SVI接口,路由接口.在多层交换机上可以将端口配置成不同类型的接口. 其中SVI接口 类似于  interface Vlan10ip address 192.168.20 ...

  10. Shell while

    while commanddo ...done c=0while [ $c -lt 5 ]do c='expr $c+1' echo $cdone