反射

反射我们以后会经常用到,这个东西实现了动态的装配,通过字符串来反射类中的属性和方法

一、反射函数

1、hasarttr(obj,name_str)

作用:判断一个对象obj中是否有对应的name_str字符串的属性或者方法

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self,food):
print("{0} is eating...{1}".format(self.name,food)) d = Dog("shabi")
choice = input(">>>:").strip() print(hasattr(d,choice)) #obj中是否有对应的choice字符串的属性或者方法 #输出
>>>:name #输入对象存在属性
True
>>>:eat #输入对象存在的方法
True

  

2、getattr(obj,name_str)

作用:根据字符串name_str获取obj对象中的对应方法的内存地址或者对应属性的值

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self,food):
print("{0} is eating...{1}".format(self.name,food)) d = Dog("shabi")
choice = input(">>>:").strip() print(getattr(d,choice)) #choice获取obj对象中的对应方法的内存地址或者对应属性的值 #输出
>>>:name #返回name属性的值
shabi
>>>:eat
<bound method Dog.eat of <__main__.Dog object at 0x00000157A129CF28>> #返回eat方法的内存地址

  

3、setattr(x,y,z)

作用:给obj对象添加一个新属性或者新方法,setattr(x, 'y', v) is equivalent to ``x.y = v''

①给对象新增一个新方法

def bulk(self):  #先定义一个bulk函数
print("{0} is yelling...".format(self.name)) class Dog(object): def __init__(self,name):
self.name = name def eat(self,food):
print("{0} is eating...{1}".format(self.name,food)) d = Dog("shabi")
choice = input(">>>:").strip() setattr(d,choice,bulk) #输入的是talk,所以又等同于d.talk = bulk
#d.talk(d) 直接写死,用d.talk(d),一般不这么写
func = getattr(d,choice) #用getattr来获取
func(d) #输出
>>>:talk
shabi is yelling...

②给对象新增一个属性

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self,food):
print("{0} is eating...{1}".format(self.name,food)) d = Dog("shabi")
choice = input(">>>:").strip() setattr(d,choice,22) #输入的是age,所以又等同于d.age = 22
# print(d.age) 这样就写死了,还是用下面一种
print(getattr(d,choice)) #输出
>>>:age
22

4、delattr(x,y)

作用:删除obj对象中的属性或者方法,delattr(x, 'y') is equivalent to ``del x.y''

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self,food):
print("{0} is eating...{1}".format(self.name,food)) d = Dog("shabi")
choice = input(">>>:").strip() delattr(d,choice) #根据字符串删除属性或者方法
print(d.name)
print(d.eat) #输出
>>>:name #删除属性name
Traceback (most recent call last):
File "E:/PycharmProjects/pythontest/day7/反射/反射.py", line 22, in <module>
print(d.name)
AttributeError: 'Dog' object has no attribute 'name'
>>>:eat #删除方法eat
Traceback (most recent call last):
File "E:/PycharmProjects/pythontest/day7/反射/反射.py", line 21, in <module>
delattr(d,choice)
AttributeError: eat

5、综合使用hasattr、getattr、setattr

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self,food):
print("{0} is eating...{1}".format(self.name,food)) d = Dog("shabi")
choice = input(">>>:").strip() if hasattr(d,choice): #判断d对象中存在属性和方法
name_value = getattr(d,choice) #获取属性值
print(name_value)
setattr(d,choice,"hong") #修改属性值
print(getattr(d,choice)) #重新获取属性的值
else:
setattr(d,choice,None) #设置不存在的属性值为None
v = getattr(d,choice)
print(v) #输出
>>>:name
shabi
hong
>>>:abc
None

最新文章

  1. Css--深入学习之折角效果
  2. PPTP(Point to Point Tunneling Protocol),即点对点隧道协议。
  3. 用Unity开发HTC VIVE——手柄控制篇
  4. 在HibernateTemplate里执行Sql语句
  5. WCF入门(二)-----实战开发
  6. 新手一步一步OpenCV+Win7+Visual Studio 2013环境配置
  7. asp.net 事件模型
  8. hibernate 多对一的情况
  9. 如何更改项目所使用的C#版本
  10. AFNetworking 保存Cookie Session 和 Webview 共享Cookie
  11. powerdesign
  12. Android进阶(十六)子线程调用Toast报Can&#39;t create handler inside thread that has not called Looper.prepare() 错误
  13. PHP Tp5.0 PHPExcel 导出操作
  14. 潭州课堂25班:Ph201805201 django 项目 第四十五课 mysql集群和负载均衡(课堂笔记)
  15. vscode wechat settings.json
  16. shell编程之helloworld
  17. 【ASP.Net MVC3 】使用Unity 实现依赖注入
  18. django rest framework restful 规范
  19. 025 Spark中的广播变量原理以及测试(共享变量是spark中第二个抽象)
  20. HttpRunner安装笔记(1)安装环境准备:pyenv安装

热门文章

  1. zabbix自定义监控项一
  2. 自动化统一安装部署tomcat
  3. 获取web应用路径 // &quot;/&quot; 表示class 根目录
  4. .aspx 页面引用命名空间
  5. 调用获取学生信息的接口,保存到excel里面的小程序
  6. SQL优化的一些总结 SQL编写一般要求
  7. 让UITableView进入编辑模式
  8. 前端性能优化--为什么DOM操作慢? 浅谈DOM的操作以及性能优化问题-重绘重排 为什么要减少DOM操作 为什么要减少操作DOM
  9. iOS CAGradientLayer白色渐变至上向下
  10. 安卓手机的后门控制工具SPADE