反射

python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)

反射机制就是在运行时,动态的确定对象的类型,并可以通过字符串调用对象属性、方法、导入模块,是一种基于字符串的事件驱动。

解释型语言:程序不需要编译,程序在运行时才翻译成机器语言,每执行一次都要翻译一次。因此效率比较低。相对于编译型语言存在的,源代码不是直接翻译成机器语言,而是先翻译成中间代码,再由解释器对中间代码进行解释运行。比如Python/JavaScript / Perl /Shell等都是解释型语言。

python是一门解释型语言,因此对于反射机制支持很好。在python中支持反射机制的函数有getattr()、setattr()、delattr()、exec()、eval()、__import__,这些函数都可以执行字符串。

eval

计算指定表达式的值。它只能执行单个表达式,而不能是复杂的代码逻辑。而且不能是赋值表达式。 单个表达式

a = "12 + 43"
b = eval(a)
print(b)#55

exec

执行复杂表达式,返回值永远都是None

b = exec("aa = 21")
print(b) # None,exec返回值为None
print(aa) # 21,exec执行了赋值语句,并定义了aa变量

执行复杂语句

a = '''ret = []
for i in range(10):
ret.append(i)'''
exec(a)
print(ret) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

导入模块

config.py

KEYWORD = 123
# 导入模块
exec("import config")
print(config.KEYWORD) # 动态创建类
class Base:
def __init__(self):
print("Base") a = "Base"
exec(a+"()")

导入模块这个功能就非常屌了,这样我们就可以动态的创建各种模块类。

eval()函数和exec()函数的区别: eval()函数只能计算单个表达式的值,而exec()函数可以动态运行代码段。 eval()函数可以有返回值,而exec()函数返回值永远为None。

再看一下下面的例子:

class Base:
def __init__(self):
print("Base") def test(self):
print("test")
return "Base::test" a = "Base"
b = eval(a+"()")
# b = eval("b.test()")
b = exec("b.test()")
print(b)

输出: test Base::test 如果不需要获取返回值,那么可以使用exec,exec("a.test()"),输出:test

虽然我们可以使用eval和exec来执行以上代码,但是这种方式有一个缺陷,假如这个属性是不存在的,那么这种调用就会报错。那么做好的方式是什么呢?先判断属性是否存在,如果存在就调用,不存在就不调用,python为我们提供了一套方法:hasattr、getattr、setattr、delattr

一、getattr

对象获取

# coding:utf-8
class Manager:
role = "管理员"
def __init__(self,name,sex,phone,mail):
self.name = name
self.sex = sex
self.phone = phone
self.mail = mail def createClass(self):
print("create class") def createTeacher(self):
print("createTeacher") def createStu(self):
print("createStu") manager = Manager("safly","男",123456,123456) print("---对象获取对象方法-----")
f = getattr(manager,"createClass")
f() print("---对象获取对象属性-----")
name = getattr(manager,"name")
print(name) print("---对象获取类属性-----")
role = getattr(manager,"role")
print(role) print("---对象获取类属性(可以设置默认值)-----")
import logging
if hasattr(manager,"role1"):
role = getattr(manager,"role1","roleDefault")
print(role)
else:
logging.warn("没有role属性")
role = getattr(manager, "role1", "roleDefault")
print(role)

运行结果:

---对象获取对象方法-----
create class
---对象获取对象属性-----
safly
---对象获取类属性-----
管理员
---对象获取类属性(可以设置默认值)-----
WARNING:root:没有role属性
roleDefault

类获取

#coding=utf-8
class Manager:
role = "管理员"
def createClass(self):
print("create class") def createStu(self):
print("createStu") m = Manager() f = getattr(Manager,"createClass")
f(Manager()) f = getattr(Manager,"createClass")
f(m) role = getattr(Manager,"createStu")
role(m) #对象获取类属性
role = getattr(Manager,"role")
print(role)

Traceback (most recent call last):
  File "E:/program/ljt_test/test/test2.py", line 13, in <module>
   f(Manager)#参数需要是类实例,忘了写括号。
TypeError: unbound method createClass() must be called with Manager instance as first argument (got classobj instance instead)

运行输出:

create class
create class
createStu
管理员

二、setattr

设置类属性、方法

class Manager:
role = "管理员"
def __init__(self,name,sex,phone,mail):
self.name = name
self.sex = sex
self.phone = phone
self.mail = mail def createClass(self):
print("create class") manager = Manager("safly","男",123456,123456) print("----设置类属性------")
setattr(Manager,"country","china")
print(Manager.country) print("----删除类属性------")
delattr(Manager,"country")
# #删除报错
# print(Manager.country)
print("----设置类方法------")
@staticmethod
def Method(cls,parm):
print u"我是被绑定的class之外的方法parm--",parm setattr(Manager,"Method",Method)
Manager.Method(Manager,1)

运行结果:

----设置类属性------
china
----删除类属性------
----设置类方法------
我是被绑定的class之外的方法parm-- 1

设置对象属性、方法

#coding=utf-8
class Manager:
role = "管理员"
def __init__(self,name,sex,phone,mail):
self.name = name
self.sex = sex
self.phone = phone
self.mail = mail def createClass(self):
print("create class") def createTeacher(self):
print("createTeacher") def createStu(self):
print("createStu") manager = Manager("safly","男",123456,123456) print("----设置对象属性------")
setattr(manager,"age",20)
print(manager.age) print("----删除对象属性------")
delattr(manager,"age")
# 'Manager' object has no attribute 'age'
# print(manager.age) print("---对象不能删除类属性---")
setattr(Manager,"country","china")
print(Manager.country)
# delattr(manager,"country")
# print(Manager.country) print("----设置对象方法------")
def create_course(self):
print('创建了一个课程') setattr(manager,'create_course',create_course)
manager.create_course(manager) def create_grade():
print('创建了一个班级')
setattr(manager,'create_grade',create_grade) manager.create_grade()
print manager.__dict__
exit(0)

运行输出结果:

----设置对象属性------
20
----删除对象属性------
---对象不能删除类属性---
china
----设置对象方法------
创建了一个课程
创建了一个班级
{'name': 'safly', 'create_course': <function create_course at 0x022F6D30>, 'create_grade': <function create_grade at 0x023744F0>, 'sex': '\xe7\x94\xb7', 'phone': 123456, 'mail': 123456}

三、模块反射

创建一个模块mokuai.py

a = 1
def method(rag):
print(rag)
return ""

然后在python.py中导入以上模块

import mokuai
print(getattr(mokuai,"a"))
method = getattr(mokuai,"method")
ret = method(8888)
print(ret)

输出如下:

1
8888
666

四、反射本模块函数、变量

#coding=utf-8
aa = 11
def method():
print("---method---")
import sys print(sys.modules[__name__])
print(getattr(sys.modules[__name__],"aa"))
f = getattr(sys.modules[__name__],"method")
f()

输出如下:

<module '__main__' from 'E:/program/ljt_test/test/test2.py'>
11
---method---

三、hasattr

hasattr(object, name)

判断object对象中是否存在name属性,当然对于python的对象而言,属性包含变量和方法;有则返回True,没有则返回False;需要注意的是name参数是string类型,所以不管是要判断变量还是方法,其名称都以字符串形式传参;getattr和setattr也同样;

#coding=utf-8
class A():
name = 'python'
def func(self):
return 'A()类的方法func()' print hasattr(A, 'name') print hasattr(A, 'age') print hasattr(A, 'func')

运行结果:

True
False
True

https://cloud.tencent.com/developer/article/1447119

https://cloud.tencent.com/developer/article/1156663

https://www.cnblogs.com/zanjiahaoge666/p/7475225.html

利用RPM和YUM安装软件的更多相关文章

  1. Linux之保留yum安装软件后的RPM包

    yum安装软件很方便,但是下载下来的rpm包在安装后默认会被删除掉: 如果希望保留yum安装的软件包该如何做呢? 设置方法: 将/etc/yum.conf里对应的keepcache参数改为1即可,然后 ...

  2. linux rpm yum 安装 软件

    rpm 安装: 1.rpm包的了解:  rpm  安装  升级  删除 rpm -ivh  ****.rpm   安装 rpm -Uvh  ****.rpm  升级 rpm -e name    删除 ...

  3. CentOS中yum安装软件时报错:No package XXX available

    yum 安装软件时,报错:No package XXX available. [root@localhost ~]# yum -y install redis Loaded plugins: fast ...

  4. yum install错误 系统环境:Oracle Linux5.4 在通过yum安装软件时出现以下错误:

    1.yum配置文件 1 [root@rh168 yum.repos.d]# cat yum.repo  2 [base] 3 name=Oracle linux  4 baseurl=file:/// ...

  5. CentOS下成功挂载xxxxxDVDx.iso并使用yum安装软件

    CentOS下成功挂载xxxxxDVDx.iso并使用yum安装软件 **不断尝试,终能到达彼岸** 测试环境为Win7 32位,VirtualBOx4.2.16+CentOS6.5,可分别到virt ...

  6. Red Hat Enterprise Linux Server(RHEL) yum安装软件时This system is not registered with RHN. RHN support will be disabled. 的解决方法(转)

    新安装了redhat6.5.安装后,登录系统,使用yum update 更新系统.提示: This system is not registered to Red Hat Subscription M ...

  7. linux 基本命令___0003 字符串处理和yum安装软件的路径

    字符串变量的处理 参考链接:SHELL字符串处理技巧 计算字符串的字符数量: ${#str} str="xxx-Lane1_S2_L001_R1_trim.fastq" echo ...

  8. 开发环境入门 linux基础(部分)虚拟内存,rpm和yum安装

    虚拟内存,rpm和yum安装 文本中查找 /内容 替换:扩展模式下(:)%s /替换目标/要替换的文件/ (只替换第一个)(后边加g全部替换) :set u添加行号 raid  lvm逻辑卷 df - ...

  9. CentOS yum安装软件时保留安装包及依赖包或者自动下载安装包及相关依赖包

    CentOS上安装某个软件一般都有很多相关的依赖包,当然,这也与我们安装时software selection步骤中选择的版本有关系,我们服务器在安装CentOS时一般选择Basic Web Serv ...

随机推荐

  1. 在linux中实现多网卡的绑定 介绍常见的7种Bond模式

    网卡bond是通过把多张网卡绑定为一个逻辑网卡,实现本地网卡的冗余,带宽扩容和负载均衡.在应用部署中是一种常用的技术,我们公司基本所有的项目相关服务器都做了bond,这里总结整理,以便待查. bond ...

  2. django admin后台接入tinymce并且支持图片上传

    首先:下载tinymce 地址是https://www.tinymce.com/ 点击download 下载社区版本即可 接着:把压缩包内tinymce目录内的所有文件和文件夹复制到Django项目中 ...

  3. 提升JavaScript递归效率:Memoization技术详解[转载]

    递归是拖慢脚本运行速度的大敌之一,太多的递归会让浏览器变得越来越慢直到死掉或者莫名其妙的突然自动退出.这里我们可以通过memoization技术来替代函数中太多的递归调用,提升JavaScript效率 ...

  4. svn取消文件夹关联的方法(svn取消关联)

    新建个记事本,贴入以下代码,保存后重命名后缀为reg,然后在目标文件夹右键就出现了删除SVN的选项了. 复制代码 代码如下: Windows Registry Editor Version 5.00[ ...

  5. (转)scala apply方法 笔记

    在akka源码中有这样一个Cluster类. 使用方法是这样的:val cluster = Cluster(context.system); 作为scala菜鸟的我,并没有找到Cluster(syst ...

  6. Tomcat 没有自动解压webapp下的war项目文件问题

    默认选择的tomcat安装在了C盘下的C:\Program Files下 所以webapp文件也在C盘下 选择启动tomcat时 我选择了 bin下的 Tomcat.exe 显示成功启动 打开项目网站 ...

  7. 解决 java.lang.ClassNotFoundException配置文件出错的问题

    出现的原因: 1.jar包没有导入 2.jar包有冲突 3.jar包没有同步发布到自己项目的lib目录中 解决方案: maven构建工程的方式:项目点击右键 点击 Properties 选择Deplo ...

  8. javascript——正則表達式

    正則表達式(RegExp对象):主要用于表单验证 1.创建正則表達式: (1).var ret = /pattern/; pattern是内容.能够是正則表達式的内容,能够是字符或是其它的内容 (2) ...

  9. VC在windows中打开文件夹并选中文件

    网上一位前辈高人的一段精髓代码让我眼前一亮…… ShellExecute(NULL, "open", "explorer.exe", "/select ...

  10. ffmpeg相关资源

    FFPLAY的原理(一) http://blog.csdn.net/shenbin1430/article/details/4291893 ubuntu12.04下命令安装ffplay等: sudo ...