calling a class method in a python module

Discussion in 'Python' started by rtuhin@gmail.com, Feb 1, 2006.

  1. Guest

    Hi

    I am trying to write a C code to call a class function in a python
    module. Here's my python module:

    def fib(n): # write Fibonacci series up to n
    a, b = 0, 1
    while b < n:
    print b,
    a, b = b, a+b

    def fib2(n): # return Fibonacci series up to n
    result = []
    a, b = 0, 1
    while b < n:
    result.append(b)
    a, b = b, a+b
    return result

    class MyClass:
    "A simple example class"
    i = 12345
    def f(self):
    return 'hello world'


    Can anybody tell me how to call "f" in my C code?

    Thanks,
    Tuhin
     
    , Feb 1, 2006
    #1
    1. Advertising

  2. > Can anybody tell me how to call "f" in my C code?

    Assuming you already have a handle to an instance of MyClass this should
    do the trick:

    PyObject *func = PyObject_GetAttrString(MyClassInst,"f");
    if(func) {
    PyObject *result = PyObject_CallObject(func,NULL);
    if(result) {
    //Do something with result
    Py_DECREF(result);
    }
    Py_DECREF(func);
    }

    Have a look in the "Python/C API Reference Manual" for more information.

    -Farshid
     
    Farshid Lashkari, Feb 1, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Sullivan WxPyQtKinter
    Replies:
    5
    Views:
    430
    Rene Pijlman
    Mar 7, 2006
  2. Replies:
    1
    Views:
    620
    Andrew Thompson
    Jan 28, 2007
  3. Farrel Lifson

    Mixin a module method as a class method

    Farrel Lifson, Oct 18, 2006, in forum: Ruby
    Replies:
    9
    Views:
    126
    Trans
    Oct 19, 2006
  4. Yu-shan Fung
    Replies:
    9
    Views:
    145
    marco antonio f.
    Mar 6, 2011
  5. Iñaki Baz Castillo
    Replies:
    3
    Views:
    154
    Iñaki Baz Castillo
    May 2, 2008
Loading...

Share This Page