反射

通过字符串映射或者修改程序运行时的状态、属性、方法, 有一下4个方法

小例子--根据用户输入调用方法:

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self):
print("%s is eating..",self.name) d= Dog('二哈')
choice = input(">>:").strip()
d.choice()
=========执行结果===========
>>:eat
Traceback (most recent call last):
File "E:/pywww/day06/11.py", line 13, in <module>
d.choice
AttributeError: 'Dog' object has no attribute 'choice'

这里用户输入的只是一个字符串,所以不会把输入的内容当作类的方法执行。

最原始的办法就是加个判断,然后判断输入的字符串是不是在这个类里有这个方法,但是这种灵活度不好。所以可以用到下面这种方法。

hasattr(obj,name_str)

输入一个字符串,判断对象有没有这个方法。

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self):
print("%s is eating.."% self.name) d= Dog('二哈')
choice = input(">>:").strip() #eat
print(hasattr(d,choice)) #True

getattr(obj,name_str)

如果是方法返回对象的内存地址,如果是属性直接返回该属性的值

print(getattr(d,choice)) #<bound method Dog.eat of <__main__.Dog object at 0x0000000000A72358>>

如果是一个不存在的方法会报错:AttributeError: 'Dog' object has no attribute 'aa'

既然是地址就说明加上括号就可以调用了:

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self):
print("%s is eating.."% self.name) d= Dog('二哈')
choice = input(">>:").strip() #eat
getattr(d,choice)() #二哈 is eating..

以上两个方法可以组合起来使用:

if hasattr(d,choice):
getattr(d,choice)() #二哈 is eating..

也可以赋值给一个变量,然后传参给方法

class Dog(object):

    def __init__(self,name):
self.name = name def eat(self,food):
print("%s is eating.."% self.name,' like ',food) d= Dog('二哈')
choice = input(">>:").strip() #eat
if hasattr(d,choice):
func = getattr(d,choice)
func('包子') #二哈 is eating.. like 包子

setattr(x,'y',v) x.y = v

添加一个方法

def bulk(self):                                                  #先定义要添加的方法
print('%s wang wang wang' % self.name) class Dog(object): def __init__(self,name):
self.name = name def eat(self,food):
print("%s is eating.."% self.name,' like ',food) d= Dog('二哈')
choice = input(">>:").strip() #bulk
if hasattr(d,choice):
func = getattr(d,choice)
func('包子')
else:
setattr(d,choice,bulk)
d.bulk(d) #bulk 是你输入的字符串 ,这里要把d传进去,不然提示你少传一个参数进去

上面是动态装载一个方法,也可以动态装载一个属性

 setattr(d,choice,22) #age
print(getattr(d,choice)) #22

delattr(obj,name_str)

动态删除属性或方法

 delattr(d,choice)

python类的反射的更多相关文章

  1. Python类总结-反射及getattr,setattr

    类反射的四个基本函数 hasattr getattr setattr delattr #反射 class BlackMedium: feature = 'Ugly' def __init__(self ...

  2. python类的反射使用方法

    曾经,博主的房东养了只金毛叫奶茶,今天就拿它当议题好了. 博主写本文时正在被广州的蚊子围攻. #反射练习 class animal(object): def __init__(self,name,fo ...

  3. Python类(五)-反射

    反射即通过字符串映射或修改程序运行时的状态.属性.方法 有4个方法: hasattr(): hasattr(object,string):object为实例化的对象,string为字符串 判断对象ob ...

  4. python(7)– 类的反射

    python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员.获取成员.设置成员.删除成员. ...

  5. python面试题~反射,元类,单例

    1 什么是反射?以及应用场景? test.py def f1(): print('f1') def f2(): print('f2') def f3(): print('f3') def f4(): ...

  6. python基础-类的反射

    1)反射是通过字符串方式映射内存中的对象. python中的反射功能是由以下四个内置函数提供:hasattr.getattr.setattr.delattr, 改四个函数分别用于对对象内部执行:检查是 ...

  7. python中的反射

    在绝大多数语言中,都有反射机制的存在.从作用上来讲,反射是为了增加程序的动态描述能力.通俗一些,就是可以让用户参与代码执行的决定权.在程序编写的时候,我们会写很多类,类中又有自己的函数,对象等等.这些 ...

  8. python面向对象进阶 反射 单例模式 以及python实现类似java接口功能

    本篇将详细介绍Python 类的成员.成员修饰符.类的特殊成员. 类的成员 类的成员可以分为三大类:字段.方法和特性. 注:所有成员中,只有普通字段的内容保存对象中,即:根据此类创建了多少对象,在内存 ...

  9. Python之路- 反射&定制自己的数据类型

    一.isinstance和issubclass isinstance(obj,cls)检查是否obj是否是类 cls 的对象 issubclass(sub, super)检查sub类是否是 super ...

随机推荐

  1. 传球游戏 dp

    题目描述 上体育课的时候,小蛮的老师经常带着同学们一起做游戏.这次,老师带着同学们一起做传球游戏. 游戏规则是这样的:nnn个同学站成一个圆圈,其中的一个同学手里拿着一个球,当老师吹哨子时开始传球,每 ...

  2. 10.Find All Anagrams in a String(在一个字符串中发现所有的目标串排列)

    Level:   Easy 题目描述: Given a string s and a non-empty string p, find all the start indices of p's ana ...

  3. javascript 中function(){}(),new function(),new Function(),Function

    和java比起来,javascript真的是松散的无以复加,不过这也让我们在无聊之余,有精力去探讨一些复杂的应用,从而在开发之路上,获得一些新的想法. javascript中的类的构造 javascr ...

  4. spring 配置 junit

    package cn.hefen.mall.app; import cn.hefen.mall.app.model.ResultMap; import cn.hefen.mall.app.model. ...

  5. 奇妙的 CSS几何图形

    三角形:通常会使用透明的border模拟出一个三角形:▲ .traingle { width:; height:; border-left: 50px solid transparent; borde ...

  6. P2913 [USACO08OCT]车轮旋转Wheel Rotation

    传送门 初始状态是 0,如果有 1 的连接,0 就变 1,如果还有 1 的连接,1 就变 0,如果是 0 的连接就不变 所以就是把答案异或上所有连接,不用考虑顺序,反正最终是一样的 #include& ...

  7. Spring和EhCache整合(针对使用了Shiro)

    https://blog.csdn.net/a243293719/article/details/78277895

  8. python3 读取表格的数据

    python3 读取表格的数据 xlrd1.1.0的下载网址:https://pypi.python.org/pypi/xlrd. xlrd1.1.0兼容python2和python3. python ...

  9. Python练习六十:网页分析,找出里面的正文与链接

    网页分析,找出里面的正文与链接 代码如下: from urllib import request from bs4 import BeautifulSoup request = request.url ...

  10. JS图片加载失败用默认图片代替

    1.onerror 事件会在文档或图像加载过程中发生错误时被触发. 当图片不存在时,将触发onerror,onerror 中img为 指定的默认图片. 图片存在则显示正常图片,图片不存在将显示默认. ...