标签:
python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author: enzhi.wang class Foo(object): def __init__(self,name): self.name = name def func(self): return "func" obj = Foo("Jack")
# 检查对象中成员 print(hasattr(obj,"name")) print(hasattr(obj,"func")) print(hasattr(obj,"age")) #检查一个没有的属性
以上代码执行结果为:
C:\Python3.5\python.exe C:/Users/root/PycharmProjects/S14/day7/反射2.py
True
True
False
# 获取成员 print(getattr(obj,"name")) print(getattr(obj,"func"))
以上代码执行结果为:
C:\Python3.5\python.exe C:/Users/root/PycharmProjects/S14/day7/反射2.py Jack <bound method Foo.func of <__main__.Foo object at 0x0000000000B325F8>>
def bulk(self): print("Foo.bulk") setattr(obj,"age",18) print(getattr(obj,"age")) setattr(obj,"talk",bulk) #obj.talk = bulk ret = getattr(obj,"talk") #ret = obj.talk ret(obj) #bulk里面没有self.name,把obj实例传进去,就获得了self.name
以上代码执行结果为:
C:\Python3.5\python.exe C:/Users/root/PycharmProjects/S14/day7/反射2.py 18 Foo.bulk
# 删除成员 delattr(obj,"name") #删除属性name,原值为‘Jack‘ print(getattr(obj,"age"))
以上代码执行结果为:
C:\Python3.5\python.exe C:/Users/root/PycharmProjects/S14/day7/反射2.py Traceback (most recent call last): File "C:/Users/root/PycharmProjects/S14/day7/反射2.py", line 34, in <module> print(getattr(obj,"age")) AttributeError: ‘Foo‘ object has no attribute ‘age‘
fanshe/ ├── core │ ├── comments.py #comments模块内部封装了三个函数 │ ├── __init__.py │ └── __pycache__ │ │ ├── index.py #index模块调用comments模块 └── __pycache__
1、comments模块中定义内容
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author: enzhi.wang def login(): print("炫酷登录页面") def logout(): print("炫酷退出页面") def home(): print("炫酷的主页面")
2、index模块中内容
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author: enzhi.wang from core import comments def run(): inp = input("请输入要访问的URL") #用户输入一个函数名 if hasattr(comments,inp): #判断用户输入的成员是否存在 func = getattr(comments,inp) #获取成员 func() else: print("啊哦!您访问的页面不存在") run()
运行index.py
标签:
原文地址:http://www.cnblogs.com/ITOps/p/5838725.html