[C++-sig] Re: static methods

David Abrahams dave at boost-consulting.com
Fri Jan 10 20:10:03 CET 2003


Nikolay Mladenov <nickm at sitius.com> writes:

> From python only:
>
>>>> class C:
> ...  def f():
> ...   return 0
> ...
>>>> C.f
> <unbound method C.f>
>>>> C.f = staticmethod(C.f)
>>>> C.f
> <unbound method C.f>
>>>> C.f()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: unbound method f() must be called with C instance as first argument (
> got nothing instead)
>
> What am I missing?

I just figured it out; my instructions missed this point as well.

Note the difference between what you did above and :

     >>> class C:
     ...    def f():
     ...       return 0
     ...    f = staticmethod(f)
     >>> C.f()
     0

The difference is that when you do this from Python, everything after
the first colon goes into a plain dictionary first, and the class is
built around it.

When you do what I told you to do, it is building a class and adding
things one-by-one to its dictionary.  Once "f" is added as a regular
function, accesses to it through C, and of course the descriptor
functionality of f takes over.

Now try this:

    >>> class C(object):
    ...     def f():
    ...             return 0
    ...
    >>> C.f = staticmethod(C.__dict__['f'])
    >>> C.f()
    0

So we could use that approach in Boost.Python

HTH,
-- 
                       David Abrahams
   dave at boost-consulting.com * http://www.boost-consulting.com
Boost support, enhancements, training, and commercial distribution





More information about the Cplusplus-sig mailing list