python: class 实例看不到自身属性

python: class instance can't see self attribute

在我的项目中,我使用 module from known bt_manager 解码 sbc 音频流。此模块 python 包装来自 rtpsbc 库的 C 函数。

class SBCCodec:
    def __init__(self, config):

            import sys

            try:
                self.codec = ffi.verify(b'#include "rtpsbc.h"',
                                        libraries=[b'rtpsbc'],
                                        ext_package=b'rtpsbc')
            except:
                print 'Exception:', sys.exc_info()[0]

            self.config = ffi.new('sbc_t *')
            self.ts = ffi.new('unsigned int *', 0)
            self.seq_num = ffi.new('unsigned int *', 0)
            self._init_sbc_config(config)
            self.codec.sbc_init(self.config, 0)

当我尝试创建 SBCCodec class 实例时,它给我:

AttributeError: SBCCodec instance has no attribute 'codec'

你可以在我上面贴的那段代码中看到这个属性。它适用于 ffi 方法(ffi.verify、ffi.new)。当我在 ipython 中输入这些命令时,一切正常,没有错误。

我错过了什么?

正如@Torxed 已经提到的,发生这种情况的唯一方法是如果 ffi.verify 在您的 try 块中抛出异常。如果发生这种情况,self.codec 将不会被初始化。如果发生这种情况,您的代码不会重新抛出异常并在简单打印后继续正常运行(这不是干净的行为)。最后的语句然后尝试调用 self.codec.config.sbc_init,即假定 self.codec 已经初始化,在这种特殊情况下这是不正确的,这就是为什么你得到 AttibuteError.

如果你想创建实例,不管 ffi.verify 在 init 开始时的失败定义 self.codec = None 并在您的最终陈述中插入一个支票,例如:

if (self.codec != None ):
   self.codec.sbc_init(self.config, 0)

希望对您有所帮助。