V2EX 首页   注册   登入
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请 登入
推荐学习书目
Python Cookbook
Using Google App Engine
推荐下载
Latest Google App Engine SDK
其他兼容技术
AppScale
Sponsored by
唐茶 字节社
中文世界最好的电子书城
V2EX  ›  Google App Engine

在用type创建类的时候遇到问题

By nttdocomo at 138 天前, 638 次点击
在__init__方法里需要调用父类的__init__方法,但super的第一个参数要求的是当前类,但调用type时当前类其实还没有创建,这个怎么办?


>>> def __init__(self):
... super(Hello, self).__init__(*args, **kwargs) #在这里其实Hello还没创建,调用肯定是失败的!
... self.message = 'Hello World'
...
>>> def say_hello(self):
... print self.message
...
>>> attrs = {'__init__': __init__, 'say_hello': say_hello}
>>> bases = (object,)
>>> Hello = type('Hello', bases, attrs)
3 回复  |  直到 2012-01-08 08:39:44 AM
    1
nttdocomo   138 天前
找到解决办法了,先临时建一个类:
class Base(object):
super(Hello, self).__init__(*args, **kwargs) #在这里其实Hello还没创建,调用肯定是失败的!
self.message = 'Hello World'

然后
Hello = type('Hello', Base, attrs)

就OK了!
    2
keakon   138 天前
你直接按第一种写法就行了,函数执行时才会去查找Hello,这时候你早就定义好了
    3
nttdocomo   138 天前
@keakon 但这里类名不是固定的,是按照不同的model类生成的,而且我的回复里写得也有问题,正确的应该是这样:
class Base(object):
def __init__(self, *args, **kwargs):
super(Base, self).__init__(*args, **kwargs) #在这里其实Hello还没创建,调用肯定是失败的!
self.message = 'Hello World'

然后
Hello = type('Hello', Base, attrs) #Hello可能不一定叫这个名字
Linode
关于   |   FAQ   |   我们的愿景   |   广告投放   |   工作空间   |   Gadget Lab   |   博客   |   上网首页   |   283 人在线   最高记录 362
创意工作者们的社区
Lovingly made by OLIVIDA
VERSION: 3.0.0-dev
♥ Do have a faith in what you're doing.