python 反射的核心本质其实就是利用字符串的形式去对象(模块)中操作(查找/获取/删除/添加)成员,一种基于字符串的事件驱动!
运行:
>>python oop_demo1.py start start func call >> bmw start ... setattr restart:restart func call >> bmw start... bmw stop... setarrt car.name >> car name: bmw car name: benz delattr restart:restart func call >> 'Car' object has no attribute 'restart'一、目录结构
└─AutoMT │ urls.py │ __init__.py │ └─controller account.py commons.py __init__.py二、代码实例
controller/account.py:
#!/usr/bin/python #coding=utf-8 def login(): print("这是一个登陆页面!") def logout(): print("这是一个退出页面!")controller/commons.py:
#!/usr/bin/python #coding=utf-8 def home(): print("这是网站主页面!")urls.py:
#!/usr/bin/python # coding=utf-8 def run(): inp = raw_input("请输入您想访问页面的url:").strip() try: modules, func = inp.split("/") try: obj = __import__("controller." + modules, fromlist=True) # 根据参数,动态的导入同名的模块,注意fromlist参数 if hasattr(obj, func): func = getattr(obj, func) func() else: print '404' except ImportError, e: print e except ValueError: print 'url不合规则,要求格式:controller/func' if __name__ == '__main__': while True: run()运行结果:
>>python urls.py 请输入您想访问页面的url:account/login 这是一个登陆页面! 请输入您想访问页面的url:commons/home 这是网站主页面! 请输入您想访问页面的url:account/register 404 请输入您想访问页面的url:houtai/home No module named houtai 请输入您想访问页面的url:
转载于:https://www.cnblogs.com/guanfuchang/p/6242285.html