V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
DAOCLOUD
推荐学习书目
Python Cookbook
Using Google App Engine
推荐下载
Latest Google App Engine SDK
其他兼容技术
AppScale
nttdocomo
V2EX  ›  Google App Engine

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

  •  
  •   nttdocomo · 2012-01-06 14:38:16 +08:00 · 4335 次点击
    这是一个创建于 4495 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在__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 条回复    1970-01-01 08:00:00 +08:00
    nttdocomo
        1
    nttdocomo  
    OP
       2012-01-06 14:59:29 +08:00
    找到解决办法了,先临时建一个类:
    class Base(object):
    super(Hello, self).__init__(*args, **kwargs) #在这里其实Hello还没创建,调用肯定是失败的!
    self.message = 'Hello World'

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

    就OK了!
    keakon
        2
    keakon  
       2012-01-06 15:15:35 +08:00
    你直接按第一种写法就行了,函数执行时才会去查找Hello,这时候你早就定义好了
    nttdocomo
        3
    nttdocomo  
    OP
       2012-01-07 08:39:43 +08:00
    @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可能不一定叫这个名字
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1102 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:15 · PVG 02:15 · LAX 11:15 · JFK 14:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.