python 反射,getattr,setattr,__import__,对象.__dict__


class Fight(object):
'''this is fight'''
def __init__(self,name):
self.name=name

def fight_status(self,status):
print('%s is status'%self.name)

f=Fight('Ca5678')
print(f.__dict__) //查看该对象的属性,如果是类则是属性和方法
choice=input('>:')
r=hasattr(f,choice)
if r:
rr=getattr(f,choice)
if type(rr)==str:
setattr(f,choice,'CA4567')
attr=getattr(f,choice)
print(attr)
else:
func=getattr(f,choice)
func('online')


getattr(obj,str) //取出属性或方法,前者直接是字符串,后者可直接调用
setattr(obj,str,value) //如果是已有属性,可重新赋值;可设置新属性
delattr(obj,str) //删除属性或方法

在模块中使用反射:
mo='sys'
m=__import__(mo)
f=getattr(m,'path')
print(f)
posted @ 2017-07-08 11:17  wangxingg  阅读(141)  评论(0)    收藏  举报