DAOCLOUD
推荐学习书目
Python Cookbook
Using Google App Engine
推荐下载
Latest Google App Engine SDK
其他兼容技术
AppScale
nttdocomo

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

  •  
  •   nttdocomo · Jan 6, 2012 · 5236 views
    This topic created in 5263 days ago, the information mentioned may be changed or developed.
    在__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 replies    1970-01-01 08:00:00 +08:00
    nttdocomo
        1
    nttdocomo  
    OP
       Jan 6, 2012
    找到解决办法了,先临时建一个类:
    class Base(object):
    super(Hello, self).__init__(*args, **kwargs) #在这里其实Hello还没创建,调用肯定是失败的!
    self.message = 'Hello World'

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

    就OK了!
    keakon
        2
    keakon  
       Jan 6, 2012
    你直接按第一种写法就行了,函数执行时才会去查找Hello,这时候你早就定义好了
    nttdocomo
        3
    nttdocomo  
    OP
       Jan 7, 2012
    @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可能不一定叫这个名字
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5805 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 02:52 · PVG 10:52 · LAX 19:52 · JFK 22:52
    ♥ Do have faith in what you're doing.