Why doesn't this method have access to its "self" argument?

dieter dieter at handshake.de
Fri Nov 20 02:18:02 EST 2015


Robert Latest via Python-list <python-list at python.org> writes:

> I'm still trying to find a simple way to implement a method (but not the
> full class) in C. Suggestions I have recived so far are good, but seem to be
> over the top for such a (seemingly) simple problem.

The C interface of Python is far from simple - and it is very easy
to make severe and difficult to analyse errors. Therefore, I confirm
an advice you already got: use "cython" (which drastically reduces
the danger of errors).

A "method" in Python is just a function which happens to get automatically
on call an additional first arguemnt: the object's reference. Apparently,
this automatism does not work for C implemented functions (at least
in Python 2). You would need to use a (so called) "descriptor" wrapper
to do this explicitely.

The easiest way (in my view), however would be:

import _my_c_implementation

class C(object):
  def my_method(self, *args, **kw):
    return _my_c_implementation.my_method(self, *args, **kw)


With a descriptor "method" (sketched above), this would become:

class C(object):
  my_method = method(_my_c_implementation.my_method)




More information about the Python-list mailing list