【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 ...
随机推荐
- python中pickle简介
2017-04-10 pickle是用来加工数据的,可以用来存取结构化数据. 例如: 一个字典a = {'name':'Timmy','age':26},用pickle.dump存到本地文件,所存数据 ...
- 2017.7.10 (windows)redis的安装
参考来自:http://www.runoob.com/redis/redis-install.html 1.下载地址 https://github.com/MSOpenTech/redis/relea ...
- eclipse maven项目导入Intellij问题处理
1.maven打包编译时后台一直输出警告信息 [WARNING] File encoding has not been set, using platform encoding GBK, i.e. b ...
- C++使用SQLite步骤及示例
C++使用SQLite步骤及示例开发环境:Windows 10+VS2013. 开发语言:C++. 1. 下载sqlite文件. 下载网址:http://www.sqlite.org/downlo ...
- axios 处理并发请求
//同时发起多个请求时的处理 axios.all([get1(), get2()]) .then(axios.spread(function (res1, res2) { // 只有两个请求都完成才会 ...
- 51单片机 | 实现SMG12864液晶显示器操作
———————————————————————————————————————————— SMG12864液晶显示器 128*64个点位,可以显示图形或8*4个汉字 - - - - - - - - - ...
- 使用transform和transition制作CSS3动画
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8& ...
- 优化MyDb
import pymysqlclass MyDb(object): #新式类 def __del__(self):#析构函数 self.cur.close() self.coon.close() pr ...
- eclipse上的git命令使用浅析,搭建Maven项目
eclipse上的git命令使用浅析 2016-03-31 14:44 关于eclipse上git的安装和建立代码仓库的文章比较多,但作为一个初识git的人更希望了解每个命令的作用. 当项目连接到 ...
- userService 用户 会员 系统设计 v2 q224 .doc
userService 用户 会员 系统设计 v2 q224 .doc 1. Admin login1 2. 普通用户注册登录2 2.1. <!-- 会员退出登录 -->2 2.2. & ...