【发布时间】:2015-01-06 01:25:42
【问题描述】:
我正在重新编码 PyCXX,它是 Python 的 C++ 包装器。
将方法添加到新样式类的原始(工作)实现涉及为每个方法创建一个“extern C”处理程序函数,使用指向这些处理程序的指针填充 PyMethodDef 表,并将 PyTypeObject 的 table->tp_methods 放置到此表中.
相反,我用覆盖 getattro 的机制替换了该机制,搜索我自己的数据以查看此属性是否具有相应的 C++ 方法,如果有,则将其打包到可调用 Python 对象中并返回它,否则遵循 PyObject_GenericGetAttr。
如果我创建一个 new_style_class 的实例,这种技术就可以工作:
# new_style_class is a C++ class deriving from ExtObj_new
_new_style_class = simple.new_style_class()
_new_style_class.func_noargs()
但是,如果我尝试从新样式类派生并从基类调用 func_noargs(),如下所示:
print( '--- Derived func ---' )
class Derived(simple.new_style_class):
def __init__( self ):
simple.new_style_class.__init__( self )
def derived_func( self ):
print( 'derived_func' )
print( vars(super()) )
super().func_noargs() # <-- AttributeError: 'super' object has no attribute 'func_noargs'
d = Derived()
d.derived_func()
... 它返回 AttributeError: 'super' object has no attribute 'func_noargs'。
我想知道问题是否来自我正在覆盖 getattro 而不是 getattr 的事实。
CPython 是否有可能在尝试调用基本属性时直接查看 base.getattr 而完全错过了 base.getattro?
如果是这样?这算不算错误?
【问题讨论】:
-
请告诉我们声明
func_noargs()的确切代码。如果它只是一个碰巧可调用的实例属性,super()可能找不到它。换句话说,如果您希望super()工作,此代码必须工作:simple.new_style_class.func_noargs(instance)。
标签: python derived-class base-class getattr