【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 ...
随机推荐
- 前端存储之Web Sql Database
前言 在上一篇前端存储之indexedDB中说到,我们项目组要搞一个前后端分离的项目,要求在前端实现存储,我们首先找到了indexedDB,而我们研究了一段时间的indexedDB后,发现它并不是很适 ...
- Node.js 极简入门Helloworld版服务器例子
粗浅得很,纯属备忘. // 内置http模块,提供了http服务器和客户端功能(path模块也是内置模块,而mime是附加模块) var http=require("http"); ...
- 原来,多年以来,我一直是个curl/CRUD程序员
curl,就是create,update,remove,list的首字母简写.说是CRUD似乎更流行些,不过无所谓,知道是一个意思就好. curl程序员,就是增改删查程序员,中文说增删改查更加顺口. ...
- NativeCode中通过JNI反射调用Java层的代码,以获取IMEI为例
简单说,就是在NativeCode中做一些正常情况下可以在Java code中做的事儿,比如获取IMEI. 这种做法会使得静态分析Java层代码的方法失效. JNIEXPORT jstring JNI ...
- Nginx探索三
这次探索一下http 请求 request 这节我们讲request,在nginx中我们指的是http请求,详细到nginx中的数据结构是ngx_http_request_t. ngx_http_re ...
- Struts2学习小结
1 基础 使用:导入 jar 包,配置 web.xml,并引入 struts.xml 文件 DMI:动态方法调用,调用时使用!分隔 action 名与方法名,如 index ! add.action, ...
- 修改pip源为国内网站
import os,sys,platformini="""[global]index-url = https://pypi.doubanio.com/simple/[in ...
- UITextView被键盘遮挡的处理
这个应该是一个通用的任务了吧,键盘弹出来的时候,UITextView(或者UITextField)会被遮挡. 解决的办法就不是很能通用了. 1. 如果有UIScrollView做父view的话只需要滚 ...
- 安装Reshaper后Intellisense失效
安装Reshaper后Intellisense失效或希望用vs2017的Intellisense功能 安装完毕后,IDE 的智能提示(Intellisense)便会默认使用 Resharper 的提示 ...
- Rabbitmq消息队列(一) centos下安装rabbitmq
1.简介 AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计.消息中间件主要用于组件之间的解耦,消息的 ...