反射在编程语言中变广泛的应用,java和php都提供专门的类库,对反射有很好的支持,而python,仿佛天生就支持了反射。
反射是在只知道类名或者函数名的情况下调用其对应的函数。广泛应用于:
- 配置文件。
- 路由。
例子1:通过import实现
module = __import__('person')
if hasattr(module, 'Person'):
person_cls = getattr(module, 'Person')
one_person = person_cls()
if hasattr(one_person, 'walk'):
func = getattr(one_person, 'walk')
func()
else:
raise Exception('method not exists')
else:
raise Exception('no cls exists')
例子2:通过globals()实现
from person import Person
p = globals()['Person']()
p.walk()
主要方法介绍
class Dog(object):
def __int__(self, name):
self.name = name
def eat(self, food):
print('I love eat '+food)
dog = Dog()
if hasattr(dog, 'name'):
func = getattr(dog, 'name')
func()
if not hasattr(dog, 'leg'):
setattr(dog, 'leg',4)
print(dog.leg)#4
例子:路由
class Dog(object):
def __int__(self, name):
self.name = name
def eat(self, food):
print('I love eat '+food)
def rout(url):
urls = url.split("&")
map = {}
for uri in urls:
u = uri.split('=')
map[u[0]] = u[1]
obj = globals()[map.get('cls')]()
func = getattr(obj, map.get('method'))
func(map.get('value'))#I love eat meat
rout("cls=Dog&method=eat&value=meat")