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

1.getattr(object, name, default = None)

根据字符串获取 obj 对象里对应 str 方法的内存地址

示例:

class Dog(object):
def __init__(self, name):
self.name = name def eat(self, food):
print('%s is eating %s' % (self.name, food)) dog1 = Dog('Dog1')
choice = input('>>').strip()
if hasattr(dog1, choice):
getattr(dog1, choice)('bone') # 根据字符串获取对象里对应方法的内存地址,传入‘bone’执行
print(getattr(dog1, choice)) # 打印属性

输出结果:

>>eat

Dog1 is eating bone

<bound method Dog.eat of <__main__.Dog object at 0x00000249C4C3B780>>

2.hasattr(object, name)

判断一个 obj 对象里是否有对应 str 字符串

示例:

class Dog(object):
def __init__(self, name):
self.name = name def eat(self, food):
print('%s is eating %s' % (self.name, food)) dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice)) # 判断一个 obj 对象里是否有对应 str 字符串

输出结果:

>>eat

True

3.setattr(object, y, v)

给类新加了一个属性等于: obj.y = v

传入属性示例:

class Dog(object):
def __init__(self, name):
self.name = name def eat(self, food):
print('%s is eating %s' % (self.name, food)) dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice)) # 判断一个 obj 对象里是否有对应 str 字符串
if hasattr(dog1, choice):
print(getattr(dog1, choice)) # 打印修改前的属性
setattr(dog1, choice, 'Dog2') # 如果属性存在,可以通过 setattr 进行修改
print(getattr(dog1, choice)) # 打印修改后的属性
else:
setattr(dog1, choice, None) # 给类新加了一个属性 == dog1.choice = None
print(getattr(dog1, choice)) # 打印新加入的属性

修改已有属性输出结果:

>>name

True

Dog1

Dog2

增加新的属性输出结果:

>>age

False

None

传入方法示例:

class Dog(object):
def __init__(self, name):
self.name = name def eat(self, food):
print('%s is eating %s' % (self.name, food)) def bulk(self): # 传入方法需要提前写好
print('%s: woof,woof!' % self.name) dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice)) # 判断一个 obj 对象里是否有对应 str 字符串
if hasattr(dog1, choice):
pass
else:
setattr(dog1, choice, bulk) # 给类新加了一个方法
dog1.bulk(dog1) # 调用新加入的方法 bulk

输出结果:

>>bulk

False

Dog1: woof,woof!

4.delattr(object, name)

删除 obj 对象中对应属性

示例:

class Dog(object):
def __init__(self, name):
self.name = name def eat(self, food):
print('%s is eating %s' % (self.name, food)) dog1 = Dog('Dog1')
choice = input('>>').strip()
print(hasattr(dog1, choice)) # 输出 True
if hasattr(dog1, choice):
delattr(dog1, choice)
print(getattr(dog1, choice)) # 打印会报错

Python 反射(reflection)的更多相关文章

  1. python 反射

    python 反射的核心本质其实就是利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动! 反射的四个基本函数使用 hasattr,getattr,setatt ...

  2. [.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦

    [.net 面向对象程序设计进阶] (21) 反射(Reflection)(下)设计模式中利用反射解耦 本节导读:上篇文章简单介绍了.NET面向对象中一个重要的技术反射的基本应用,它可以让我们动态的调 ...

  3. [.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程

    [.net 面向对象程序设计进阶] (20) 反射(Reflection)(上)利用反射技术实现动态编程 本节导读:本节主要介绍什么是.NET反射特性,.NET反射能为我们做些什么,最后介绍几种常用的 ...

  4. python反射

    python反射 python的反射是基于字符串的形式去对象(模块)中操作其成员.此操作是动态的,常用于web开发中url参数中对应模块或者函数的反射. 下面开始具体说明: 场景需求: 我的pytho ...

  5. [整理]C#反射(Reflection)详解

    本人理解: 装配件:Assembly(程序集) 晚绑定:后期绑定 MSDN:反射(C# 编程指南) -----------------原文如下-------- 1. 什么是反射2. 命名空间与装配件的 ...

  6. CSharpGL(43)环境映射(Environment Mapping)-天空盒(Skybox)反射(Reflection)和折射(Refraction)

    CSharpGL(43)环境映射(Environment Mapping)-天空盒(Skybox)反射(Reflection)和折射(Refraction) 开始 如图所示,本文围绕GLSL里的sam ...

  7. 代理(Proxy)和反射(Reflection)

    前面的话 ES5和ES6致力于为开发者提供JS已有却不可调用的功能.例如在ES5出现以前,JS环境中的对象包含许多不可枚举和不可写的属性,但开发者不能定义自己的不可枚举或不可写属性,于是ES5引入了O ...

  8. Python反射机制理解

    Python反射机制用沛齐老师总结的话说就是:利用字符串的形式去对象(模块)中操作(寻找)成员. getattr(object, name) object代表模块,name代表模块中的属性或成员,该函 ...

  9. Golang 反射reflection

    反射reflection 反射可大大提高程序的灵活性,使得interface{}有更大的发挥余地 反射使用TypeOf和ValueOf函数从接口中获取目标对象信息 反射会将匿名字段作为独立字段(匿名字 ...

随机推荐

  1. 软件测试:第二次作业(JUnit单元测试方法)

    一.JUnit是什么? JUnit是由 Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework).JUnit测试是程序员测试, ...

  2. Linux 操作系统目录结构

    /  根目录 # ls /bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp  var bin - ...

  3. Redis 攻击还原Linux提权入侵的相关说明

    https://files.cnblogs.com/files/fudong071234/redis_crackit_v1.1%E2%80%94%E2%80%94redis%E6%94%BB%E5%8 ...

  4. react中Redux应用框架学习

    1. 最普通的react-redux 2.应用context的傻瓜组件和聪明组件的redux框架  3. 精简版react-redux,利用react-redux模块的redux(推荐)  4.多个模 ...

  5. python中的 uuid 模块使用示例

    此模块提供不可变的 UUID 对象 (类 uuid) 和函数uuid1().uuid3().uuid4().uuid5(), 用于生成在 RFC 4122 中指定版本1.3.4和5UUIDs .如果你 ...

  6. 《Pro SQL Server Internals, 2nd edition》15w

    第三章 统计 SQL Server查询优化器在为查询选择执行计划时使用基于成本的模型.它估计不同执行计划的成本,并选择成本最低的一个.但是,请记住,SQL Server并不搜索可用于查询的最佳执行计划 ...

  7. linux 常用命令及实例

    转载:https://www.cnblogs.com/xiaoyafei/p/9163976.html 在linux中,绝大多数命令都参照 命令 选项 参数 选项:适用于调整命令的功能的 参数:指的是 ...

  8. redis概述(一)

    什么是NoSql? 为了解决高并发.高可用.高可扩展,大数据存储等一系列问题而产生的数据库解决方案,就是NoSql. NoSql,叫非关系型数据库,它的全名Not only sql.它不能替代关系型数 ...

  9. Beta发布用户使用报告

    用户数量:13人 姓名如下(包括化名):张小斌.王瑞瑞.蛋蛋.小美.晨曦.小丽.张利刚.小闫.小谢.小崔.小欢欢.小胡胡.小霞霞 寻找的用户多为王者荣耀交流协会成员的同学,对PSP Daily软件有极 ...

  10. VScode编辑器使用

    快捷键: shift + alt + F 格式化