反射

class Dog(object):
    def __init__(self,name):
        self.name =name
    def eat(self,food):
        print("%s is eating " %self.name,food)
d = Dog("NiuHanYang")
choice = input(">>:").strip()

if hasattr(d,choice):
    func = getattr(d,choice)
    func("chenronghua")

 

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

hasattr(obj,name_str) , 判断一个对象obj里是否有对应的name_str字符串的方法

getattr(obj,name_str) ,根据字符串去获取obj对象里的对应的方法里的内存地址

setattr(obj,'y',z), is equivalent to ''x.y = v''

delattr   删除

 

例子:

def bulk(self):
    print("%s is yelling..." %self.name)
class Dog(object):
    def __init__(self,name):
        self.name =name
    def eat(self,food):
        print("%s is eating " %self.name,food)

d = Dog("NiuHanYang")
choice = input(">>:").strip()

if hasattr(d,choice):
    getattr(d,choice)
else:
    setattr(d,choice,bulk) #d.talk = bulk
    func = getattr(d,choice)
    func(d)

 

 

动态导入模块

 

 

1 import importlib
2  
3 __import__('import_lib.metaclass') #这是解释器自己内部用的
4 #importlib.import_module('import_lib.metaclass') #与上面这句效果一样,官方建议用这个

 

posted @ 2017-09-15 08:30  _Cohen  阅读(100)  评论(0)    收藏  举报