面向对象【day08】:反射(五)
本节内容
- 概述
- 反射函数
- 综合使用
一、概述
反射我们以后会经常用到,这个东西实现了动态的装配,通过字符串来反射类中的属性和方法
二、反射函数
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))d = 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))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方法的内存地址 |
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))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)#输出>>>:talkshabi 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))d = Dog("shabi")choice = input(">>>:").strip()setattr(d,choice,22) #输入的是age,所以又等同于d.age = 22# print(d.age) 这样就写死了,还是用下面一种print(getattr(d,choice))#输出>>>:age22 |
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))d = Dog("shabi")choice = input(">>>:").strip()delattr(d,choice) #根据字符串删除属性或者方法print(d.name)print(d.eat)#输出>>>:name #删除属性nameTraceback (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 #删除方法eatTraceback (most recent call last): File "E:/PycharmProjects/pythontest/day7/反射/反射.py", line 21, in <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))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)#输出>>>:nameshabihong>>>:abcNone |
面向对象【day08】:反射(五)的更多相关文章
- Python 面向对象之反射
Python 面向对象之反射 TOC 什么是反射? hasattr getattr setattr delattr 哪些对象可以使用反射 反射的好处 例子一 例子二 什么是反射? 程序可以访问.检查和 ...
- Python之面向对象进阶------反射(Day26)
一 classmethod class Classmethod_Demo(): role = 'dog' @classmethod def func(cls): print(cls.role) Cla ...
- python 面向对象之反射及内置方法
面向对象之反射及内置方法 一.静态方法(staticmethod)和类方法(classmethod) 类方法:有个默认参数cls,并且可以直接用类名去调用,可以与类属性交互(也就是可以使用类属性) 静 ...
- 百万年薪python之路 -- 面向对象之 反射,双下方法
面向对象之 反射,双下方法 1. 反射 计算机科学领域主要是指程序可以访问.检测和修改它本身状态或行为的一种能力(自省) python面向对象中的反射:通过字符串的形式操作对象相关的属性.python ...
- SOLID:面向对象设计的五个基本原则
在程序设计领域,SOLID 是由罗伯特·C·马丁在 21 世纪早期引入的记忆术首字母缩略字,指代了面向对象编程和面向对象设计的五个基本原则.当这些原则被一起应用时,它们使得一个程序员开发一个容易进行软 ...
- Python面向对象之-反射
Python中一切皆对象,在Python中的反射:通过字符串的形式操作对象的属性 hasattr 判断是否有改属性或者方法,有返回True,没有返回false getattr 如果是属性获得该属性 ...
- 面向对象之反射 与__str__等内置函数
一 反射 1.面向对象中的反射:通过字符串的形式操作对象的相关属性,python中一切事物都是属性(都可以使用反射) 四个可以实现自省<反射>的函数:hasattr / getattr ...
- day28 面向对象:反射,内置函数,类的内置方法
面向对象进阶博客地址链接: http://www.cnblogs.com/Eva-J/articles/7351812.html 复习昨日内容: # 包 # 开发规范 # # hashlib # 登录 ...
- python基础之 面向对象之反射
1.isinstance和issubclass issubclass(Son,Foo) 判断雷与类之间的是否有继承关系,接受两个参数,一个是疑似子类,一个是疑似父类,判断Son是否是Foo的子类 ob ...
- C++面向对象高级编程(五)类与类之间的关系
技术在于交流.沟通,转载请注明出处并保持作品的完整性. 本节主要介绍一下类与类之间的关系,也就是面向对象编程先介绍两个术语 Object Oriented Programming OOP面向对象编 ...
随机推荐
- 《面向对象程序设计》第三次作业 Calculator
c++第三次作业 Calculator git上的作业展示点这里. ps:有一点不是很明确,作业要求:将数字和符号提取出来,得到一组string,然后才将这些string存入队列中.按我的理解是需要将 ...
- Caffe2的安装
源码下载 首先下载caffe2的源码:https://github.com/caffe2/caffe2 网上都建议使用git命令下载,因为caffe2依赖了很多第三方模块,git会根据依赖自动下载第三 ...
- PAT 1009 说反话
https://pintia.cn/problem-sets/994805260223102976/problems/994805314941992960 给定一句英语,要求你编写程序,将句中所有单词 ...
- nginx for Windows Known issues:path
http://nginx.org/en/docs/windows.html nginx/Windows uses the directory where it has been run as the ...
- Undertow的InMemorySessionManager
https://github.com/undertow-io/undertow/blob/master/core/src/main/java/io/undertow/server/session/In ...
- Tomcat7解决java.lang.OutOfMemoryError: PermGen space
上述两参数,可根据实际情况,逐渐调大.
- vue的使用1
Vue.$set(object, key, value); <!-- Alt + C --> <input @keyup.alt.="clear"> < ...
- [转]curl的详细使用
转自:http://www.cnblogs.com/gbyukg/p/3326825.html 下载单个文件,默认将输出打印到标准输出中(STDOUT)中 curl http://www.centos ...
- 一步步分析为什么B+树适合作为索引的结构
在MySQL中,主要有四种类型的索引,分别为:B-Tree索引,Hash索引,Fulltext索引和R-Tree索引,本文讲的是B-Tree索引. 什么是索引 索引(Index)是帮助数据库高效获取数 ...
- js對象構造
創建對象的3種方式: 1. var a=new Object() a.attributes=“1”: 2. var a={attributes:"1",aa:"2&quo ...