python使用装饰器定义多个类

时间:2013-07-01 11:09:30

标签: python python-2.7 metaprogramming tornado

我有基类:

class BaseGameHandler(BaseRequestHandler):
    name = 'Base'
    def get(self):
        self.render(self.name + ".html")

现在,我需要定义一些这样的子类,但问题是,他们必须有一个装饰器。等效代码为:

@route('asteroid')
class AsteroidGameHandler(BaseGameHandler):
    name = 'asteroid'


@route('blah')
class BlahGameHandler(BaseGameHandler):
    name = 'blah'

也许还有一些。 这里有一点背景:这是一个龙卷风网络应用程序,@route装饰器允许您将/blah映射到BlahGameHandler。此代码将/blah映射到BlahGameHandler,将/asteroid映射到AsteroidGameHandler

所以我认为我应该在python中使用元编程并动态定义所有这些类。我尝试了以下哪些不起作用(并且不起作用我的意思是最终的网络应用程序在/asteroid/blah上抛出404):

game_names = ['asteroid', 'blah']

games = list([game, type('%sGameHandler' % (game.title()), (BaseGameHandler,), {'name': game})] for game in game_names)

for i in xrange(len(games)):
    games[i][1] = route(games[i][0])(games[i][1])

我错过了什么?这两个代码在运行时是否相同?

1 个答案:

答案 0 :(得分:0)

您使用的库仅在模块中查找全局类对象。

将每个类设置为全局; globals() function使您可以作为字典访问模块名称空间:

for i in xrange(len(games)):
    globals()[games[i][1].__name__] = route(games[i][0])(games[i][1])

include()代码在列表中查找您的观看次数。

具体而言,include()使用以下循环来检测处理程序:

for member in dir(module):
    member = getattr(module, member)
    if isinstance(member, type) and issubclass(member, web.RequestHandler) and hasattr(member, 'routes'):
        # ...
    elif isinstance(member, type) and issubclass(member, web.RequestHandler) and hasattr(member, 'route_path'):
        # ...
    elif isinstance(member, type) and issubclass(member, web.RequestHandler) and hasattr(member, 'rest_route_path'):
        # ...

dir(module)仅考虑顶级对象。