V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
DAOCLOUD
推荐学习书目
Python Cookbook
Using Google App Engine
推荐下载
Latest Google App Engine SDK
其他兼容技术
AppScale
nttdocomo

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

  •  
  •   nttdocomo · Jan 6, 2012 · 5193 views
    This topic created in 5237 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   ·   2790 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 01:42 · PVG 09:42 · LAX 18:42 · JFK 21:42
    ♥ Do have faith in what you're doing.