本节内容

  1. 概述
  2. 反射函数
  3. 综合使用

一、概述

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

二、反射函数

2.1 hasarttr(obj,name_str)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
print(hasattr(d,choice))  #obj中是否有对应的choice字符串的属性或者方法
 
#输出
>>>:name  #输入对象存在属性
True
>>>:eat  #输入对象存在的方法
True

2.2 getattr(obj,name_str)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= 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方法的内存地址

2.3 setattr(x,y,z)

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

①给对象新增一个新方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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))
 
= 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...

②给对象新增一个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= Dog("shabi")
choice = input(">>>:").strip()
 
setattr(d,choice,22)  #输入的是age,所以又等同于d.age = 22
# print(d.age) 这样就写死了,还是用下面一种
print(getattr(d,choice))
 
#输出
>>>:age
22

2.4  delattr(x,y)

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= 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 22in <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 21in <module>
    delattr(d,choice)
AttributeError: eat

三、综合使用

3.1 综合使用hasattr、getattr、setattr

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Dog(object):
 
    def __init__(self,name):
        self.name = name
 
    def eat(self,food):
        print("{0} is eating...{1}".format(self.name,food))
 
= 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
    = getattr(d,choice)
    print(v)
 
#输出
>>>:name
shabi
hong
>>>:abc
None

最新文章

  1. SSIS Design4: 处理外键
  2. (原创)提取Xilinx开发工具的迅雷下载地址
  3. 更新日志 - BugHD iOS 客户端上线
  4. 【转】关于TCP和UDP协议消息保护边界的介绍
  5. bash read命令用法
  6. Linq的延迟
  7. POJ 2886 Who Gets the Most Candies? 线段树
  8. 「Poetize7」足球比赛
  9. Java学习笔记-File类的基本方法
  10. WebLogic使用SSH架构部署遇到org.hibernate.hql.internal.ast.HqlTok
  11. 利用反射来实现获取成员的指定特性(Attribute)信息
  12. PHP数据库45道题整理~~~啦啦啦
  13. 结合java.util.TreeMap源码理解红黑树
  14. html 中 xmp标记
  15. 找出 Xcode 编译C/C++过程文件及生成文件
  16. Django学习笔记之视图高级-HTTP请求与响应
  17. poj 1523&quot;SPF&quot;(无向图求割点)
  18. python成长之路五-文件操作
  19. mac brew安装mysql
  20. LeetCode 11 Container With Most Water(分支​判断问题)

热门文章

  1. 软件工程APP进度更新
  2. 如何使squild服务只能使用自定义的端口号
  3. shell之重定向
  4. 防止xss攻击。
  5. mysql问题处理积累
  6. 洛谷 P4878 [USACO05DEC]layout布局
  7. OpenGL 使用 PBO 高速复制屏幕图像到内存或者纹理中
  8. hdu1176 (免费馅饼)
  9. 【题解】 bzoj3036: 绿豆蛙的归宿 (期望dp)
  10. Leetcode 237.删除链表中的节点 By Python