通过字符串的形式操作对象的成员, 叫做反射.
- class Foo:
- def __init__(self,name,age):
- self.name = name
- self.age = age
- def show(self):
- return ('{} - {}'.format(self.name,self.age))
- obj = Foo('test_name',34)
- print (getattr(obj,'name'))
- print (hasattr(obj,'age'))
- setattr(obj,'k1','v1')
- print (getattr(obj,'k1'))
- delattr(obj,'age')
- print (getattr(obj,'age'))
- # test_name
- # print (getattr(obj,'age'))
- # True
- # AttributeError: 'Foo' object has no attribute 'age'
- # v1
- getattr
- hasattr
- setattr
- delattr
- class Foo:
- def index(self):
- return 'index'
- def new(self):
- return ('is new page')
- def test(self):
- return ('is test page')
- f = Foo()
- while True:
- input_str = input('Please input URL:')
- if input_str == 'back' or input_str == 'b':
- break
- if hasattr(f,input_str):
- get_func = getattr(f,input_str)
- print (get_func())
- else:
- print ('404 page')
来源: http://www.bubuko.com/infodetail-2571823.html