【python】-- 类的反射
反射
反射我们以后会经常用到,这个东西实现了动态的装配,通过字符串来反射类中的属性和方法
一、反射函数
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
【python】-- 类的反射的更多相关文章
- Python类总结-反射及getattr,setattr
类反射的四个基本函数 hasattr getattr setattr delattr #反射 class BlackMedium: feature = 'Ugly' def __init__(self ...
- python类的反射使用方法
曾经,博主的房东养了只金毛叫奶茶,今天就拿它当议题好了. 博主写本文时正在被广州的蚊子围攻. #反射练习 class animal(object): def __init__(self,name,fo ...
- Python类(五)-反射
反射即通过字符串映射或修改程序运行时的状态.属性.方法 有4个方法: hasattr(): hasattr(object,string):object为实例化的对象,string为字符串 判断对象ob ...
- python类的反射
反射 通过字符串映射或者修改程序运行时的状态.属性.方法, 有一下4个方法 小例子--根据用户输入调用方法: class Dog(object): def __init__(self,name): s ...
- python(7)– 类的反射
python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员.获取成员.设置成员.删除成员. ...
- python面试题~反射,元类,单例
1 什么是反射?以及应用场景? test.py def f1(): print('f1') def f2(): print('f2') def f3(): print('f3') def f4(): ...
- python基础-类的反射
1)反射是通过字符串方式映射内存中的对象. python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr, 改四个函数分别用于对对象内部执行:检查是 ...
- python中的反射
在绝大多数语言中,都有反射机制的存在.从作用上来讲,反射是为了增加程序的动态描述能力.通俗一些,就是可以让用户参与代码执行的决定权.在程序编写的时候,我们会写很多类,类中又有自己的函数,对象等等.这些 ...
- python面向对象进阶 反射 单例模式 以及python实现类似java接口功能
本篇将详细介绍Python 类的成员.成员修饰符.类的特殊成员. 类的成员 类的成员可以分为三大类:字段.方法和特性. 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存 ...
- Python之路- 反射&定制自己的数据类型
一.isinstance和issubclass isinstance(obj,cls)检查是否obj是否是类 cls 的对象 issubclass(sub, super)检查sub类是否是 super ...
随机推荐
- [Angular] Dynamic component rendering by using *ngComponentOutlet
Let's say you want to rending some component based on condition, for example a Tabs component. Insid ...
- SpringMVC 下载XLS文档的设置
页面设置参考上文.SpringMVC 下载文本文档的设置 此文是关于xls文档下载的,这个文档使用Apache的POI生成,需要的jar包可以从下面地址下载: http://pan.baidu.com ...
- Activity和Service交互之bindService(回调更新UI)
一.回调接口 public interface OnProgressListener { void onProgress(int progress); } 二.Service代码 public cla ...
- datatables插件适用示例
本文共四部分:官网 | 基本使用|遇到的问题|属性表 一:官方网站:[http://www.datatables.NET/] 二:基本使用:[http://www.guoxk.com/node/jQu ...
- sed `grep` 查找并替换
sed "s/libletvwatermark/libletv_watermark/" `grep -rl libletvwatermark` grep [options] 3.主 ...
- 10分钟-jQuery-基础选择器
1.id 选择器 jquery能使用CSS选择器来操作网页中的标签元素.假设你想要通过一个id号去查找一个元素,就能够使用例如以下格式的选择器: $("#my_id") 当中#my ...
- JavaWeb Session详解
代码地址如下:http://www.demodashi.com/demo/12756.html 记得把这几点描述好咯:代码实现过程 + 项目文件结构截图 + ## Session的由来 上一篇博文介绍 ...
- 关于清理 mac 其他文件的的方法
mac 用于开发使用时间长硬盘会越来越小,速度越来越慢的, 亦是花了几分钟研究怎么清理系统的缓存, 方法: 1,到 https://www.omnigroup.com/more/ 安装 OmniDis ...
- ZAP介绍
Zed Attack Proxy简写为ZAP,是一个简单易用的渗透测试工具,是发现Web应用中的漏洞的利器,更是渗透测试爱好者的好东西.ZAP下载地址:https://www.owasp.org/in ...
- macOS10.12部署sonarqube5.6.3
所需安装包已全部上传云盘:https://pan.baidu.com/s/1i5LvOCd 密码:s47e 1. 安装mysql 下载云盘的dmg包,一路默认安装,注意:一定要记住最后一步弹出的默认密 ...