反射,通过字符串映射到对象属性

class People:
country='China' def __init__(self,name,age):
self.name=name
self.age=age def talk(self):
print('%s is talking' %self.name) p = People("gd", 22)
print(p.name) # p.__dic__['name']
print(p.talk) # <bound method People.talk of <__main__.People object at 0x00000000027B7470>> print(hasattr(p, 'name')) # True 判断 对象p 里有没有 name 属性, hasattr(),第一个参数传对象,第二个参数传 属性名
print(hasattr(p, 'talk1')) # True print(getattr(p, 'name')) # gd 拿到 对象 p 里的属性
# print(getattr(p, 'name2')) # AttributeError: 'People' object has no attribute 'name2'
# getattr(), 没有相应属性的时候,会报错,我们可以传入第三个参数
print(getattr(p, 'name2', None)) # None 这样,找不到属性的时候就会返回 None 了 setattr(p, 'sex', '机器大师')
print(p.sex) # 机器大师 print(p.__dict__) # {'name': 'gd', 'age': 22, 'sex': '机器大师'}
delattr(p, 'sex') # 删除属性
print(p.__dict__) # {'name': 'gd', 'age': 22} # hasattr() getattr() setatter() delattr() 不仅适用于对象,也可以用于类
print(hasattr(People, 'country')) # True
print(getattr(People, 'country')) # China

反射的应用

class Service:
def run(self):
while True:
cmd = input(">>:").strip()
if hasattr(self, cmd):
func = getattr(self, cmd)
func() def get(self):
print('get......') def put(self):
print('put.....') obj = Service()
obj.run() # >>:get
# get......
# >>:put
# put.....

最新文章

  1. Python中的网络编程
  2. Silverlight动态生成控件实例
  3. Android深度探索--HAL与驱动开发----第五章读书笔记
  4. nba技能表
  5. Flipping elements with WPF
  6. BestCoder Round #74
  7. mysql概要(四)order by,group 的特点,子查询
  8. selenium+python自动化之操作浏览器
  9. ASP.NET FormsAuthentication跨站点登录时绝对地址返回的问题
  10. 另一种数据库连接字符串的编写方式(Sqlbuilder)
  11. 遗传算法Matlab源程序
  12. vhost:一种 virtio 高性能的后端驱动实现
  13. 安装SQL server 2008 R2和QL server 2008,与SQL server 2008升级SQL server 2008 R2
  14. day09--函数的定义分类以及其使用(1)
  15. 斯坦福大学公开课机器学习:advice for applying machine learning | model selection and training/validation/test sets(模型选择以及训练集、交叉验证集和测试集的概念)
  16. Bringing Native Performance to Electron
  17. Kafka命令行操作及常用API
  18. vue的组件之间传值方法
  19. 关于itext生成pdf的新的demo(包含简单的提取txt文件的内容 和xml内容转化为pdf)
  20. python之join

热门文章

  1. lua &quot;诡异&quot;的return用法
  2. thinkphp执行流程
  3. Tomcat 启动很慢?
  4. Android开发过程中部分报错解决方法。
  5. c# 文件名排序
  6. 从零开始的全栈工程师——html篇1.2
  7. BZOJ2438: [中山市选2011]杀人游戏(tarjan)
  8. Drupal Module Hooks
  9. Spring应用开发常见规范
  10. ArcGIS Engine从服务器(ArcSDE geodatabases)读取数据