首页 > 代码库 > Python 反射

Python 反射


反射:

可以结合工厂模式一起学习!

#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = ‘gaogd‘
‘‘‘
反射
‘‘‘

class Myclass(object):
    name = ‘test‘

    def sayhi(self):
        print " sayhi"

    def info(self):
        pass

def run():
    print "runing outside the class"


m = Myclass()
user_input = ‘test‘

‘‘‘
if user_input == ‘sayhi‘:
    m.sayhi()
‘‘‘

if hasattr(m,user_input):
    func = getattr(m,user_input)
    func()
else:
    print ‘user input not exist: ‘,user_input
    setattr(m,user_input,run)

    f = getattr(m,user_input)
    f()
    print  ‘run test.but call run‘,m.test()


#print m.__dict__



反射实例2:

#!/usr/bin/python
# -*- coding: utf-8 -*-

__author__ = ‘gaogd‘
‘‘‘
反射
‘‘‘

class Myclass(object):
    name = ‘test‘

    def sayhi(self):
        print " sayhi"

    def sayhello(self):
        print " sayhello"

    def sayno(self):
        print " sayno"

    def sayyes(self):
        print " yes"



    def put_say(self,say):

        if hasattr(m,say):
            func = getattr(m,say)
            func()
        else:
            print ‘user input not exist: ‘, say



m = Myclass()
while True:
    user_input = raw_input(u"输入你想要调用的方法: ")
    m.put_say(user_input)
输入你想要调用的方法: sayno
 sayno
输入你想要调用的方法: sayyes
 yes
输入你想要调用的方法: sayhi
 sayhi
输入你想要调用的方法: nosay
user input not exist:  nosay
输入你想要调用的方法:


相关知识点:

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431866385235335917b66049448ab14a499afd5b24db000


技术分享

本文出自 “奋斗吧” 博客,转载请与作者联系!

Python 反射