参考dive into python P142
#coding:utf-8
'''locals()字典接收全局的类名称,从而获得类,然后实例化该类,调用实例的方法
'''
#定义类 myclass
class myclass:
def __init__(self):
self.name = "sam"
def report(self):
print self.name
#定义类 myroom
class myroom:
def __init__(self):
self.room="Home"
def report(self):
print self.room
#对类进行分发
def getclass(classname):
print "Locals:",globals()
#获取类名,保存在myclass变量中
myclass= globals()[classname]
#得到类的实例
myinstance = myclass()
#调用实例的report方法
myinstance.report()
if __name__ == '__main__':
for i in ["class","room"]:
classname ="my"+i
getclass(classname)
或:
#对类进行分发
def getclass():
#获得类
classes = [classmodel for classkey,classmodel in globals().items() if classkey.startswith("my")]
print classes
for myclass in classes:
# 对类进行实例化
cc=myclass()
cc.report()
if __name__ == '__main__':
getclass()
#结果:
[<class __main__.myclass at 0x044E84C8>, <class __main__.myroom at 0x0452A260>]
sam
Home
版权声明:本文为博主原创文章,未经博主允许不得转载。