[pypy-issue] [issue1676] cppyy: Incorrect __class__ for Python subclasses of C++ classes

Alex Stewart tracker at bugs.pypy.org
Fri Jan 17 20:54:38 CET 2014

New submission from Alex Stewart <foogod at gmail.com>:

(The cppyy docs sorta imply that this sort of thing (subclassing C++ classes 
from Python) should be possible, so I'm assuming this is a bug..)

If I have a C++ class (say, "CppClass") imported via cppyy, and create a 
subclass of this in Python like so:

class MyClass (cppyy.gbl.CppClass):
    def myfunc(self):
        print "Yay!"

When I create an instance of MyClass, what I actually get back is an instance of 
CppClass, not of MyClass, so I can't actually use the additional 
attributes/methods defined on the subclass:

>>>> o = MyClass()
>>>> o.__class__
<class '__main__.CppClass'>
>>>> isinstance(o, MyClass)
>>>> o.myfunc()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'CppClass' object has no attribute 'myfunc'

I notice, however, that if I override __new__ and explicitly fix the __class__ 
attribute of the returned object, things actually do seem to work as expected:

class MyClass (cppyy.gbl.CppClass):
    def __new__(cls):
        o = cppyy.gbl.CppClass.__new__(cls)
        o.__class__ = cls
        return o

    def myfunc(self):
        print "Yay!"

>>>> o = MyClass()
>>>> o.__class__
<class '__main__.MyClass'>
>>>> isinstance(o, MyClass)
>>>> o.myfunc()

(And I can still access all the C++ members from the parent class as expected 

It looks like the default cppyy __new__ constructor is just not setting 
__class__ correctly on the created object?

messages: 6491
nosy: Foogod, pypy-issue
priority: bug
release: 2.2
status: unread
title: cppyy: Incorrect __class__ for Python subclasses of C++ classes

PyPy bug tracker <tracker at bugs.pypy.org>

More information about the pypy-issue mailing list