Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 532051
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T09:21:54+00:00 2026-05-13T09:21:54+00:00

Consider the following Python (3.x) code: class Foo(object): def bar(self): pass foo = Foo()

  • 0

Consider the following Python (3.x) code:

class Foo(object):
    def bar(self):
        pass
foo = Foo()

How to write the same functionality in C?

I mean, how do I create an object with a method in C? And then create an instance from it?

Edit:
Oh, sorry! I meant the same functionality via Python C API. How to create a Python method via its C API?
Something like:

PyObject *Foo = ?????;
PyMethod??? *bar = ????;
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T09:21:54+00:00Added an answer on May 13, 2026 at 9:21 am

    Here’s a simple class (adapted from http://nedbatchelder.com/text/whirlext.html for 3.x):

    #include "Python.h"
    #include "structmember.h"
    
    // The CountDict type.
    
    typedef struct {
       PyObject_HEAD
       PyObject * dict;
       int count;
    } CountDict;
    
    static int
    CountDict_init(CountDict *self, PyObject *args, PyObject *kwds)
    {
       self->dict = PyDict_New();
       self->count = 0;
       return 0;
    }
    
    static void
    CountDict_dealloc(CountDict *self)
    {
       Py_XDECREF(self->dict);
       self->ob_type->tp_free((PyObject*)self);
    }
    
    static PyObject *
    CountDict_set(CountDict *self, PyObject *args)
    {
       const char *key;
       PyObject *value;
    
       if (!PyArg_ParseTuple(args, "sO:set", &key, &value)) {
          return NULL;
       }
    
       if (PyDict_SetItemString(self->dict, key, value) < 0) {
          return NULL;
       }
    
       self->count++;
    
       return Py_BuildValue("i", self->count);
    }
    
    static PyMemberDef
    CountDict_members[] = {
       { "dict",   T_OBJECT, offsetof(CountDict, dict), 0,
                   "The dictionary of values collected so far." },
    
       { "count",  T_INT,    offsetof(CountDict, count), 0,
                   "The number of times set() has been called." },
    
       { NULL }
    };
    
    static PyMethodDef
    CountDict_methods[] = {
       { "set",    (PyCFunction) CountDict_set, METH_VARARGS,
                   "Set a key and increment the count." },
       // typically there would be more here...
    
       { NULL }
    };
    
    static PyTypeObject
    CountDictType = {
       PyObject_HEAD_INIT(NULL)
       0,                         /* ob_size */
       "CountDict",               /* tp_name */
       sizeof(CountDict),         /* tp_basicsize */
       0,                         /* tp_itemsize */
       (destructor)CountDict_dealloc, /* tp_dealloc */
       0,                         /* tp_print */
       0,                         /* tp_getattr */
       0,                         /* tp_setattr */
       0,                         /* tp_compare */
       0,                         /* tp_repr */
       0,                         /* tp_as_number */
       0,                         /* tp_as_sequence */
       0,                         /* tp_as_mapping */
       0,                         /* tp_hash */
       0,                         /* tp_call */
       0,                         /* tp_str */
       0,                         /* tp_getattro */
       0,                         /* tp_setattro */
       0,                         /* tp_as_buffer */
       Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags*/
       "CountDict object",        /* tp_doc */
       0,                         /* tp_traverse */
       0,                         /* tp_clear */
       0,                         /* tp_richcompare */
       0,                         /* tp_weaklistoffset */
       0,                         /* tp_iter */
       0,                         /* tp_iternext */
       CountDict_methods,         /* tp_methods */
       CountDict_members,         /* tp_members */
       0,                         /* tp_getset */
       0,                         /* tp_base */
       0,                         /* tp_dict */
       0,                         /* tp_descr_get */
       0,                         /* tp_descr_set */
       0,                         /* tp_dictoffset */
       (initproc)CountDict_init,  /* tp_init */
       0,                         /* tp_alloc */
       0,                         /* tp_new */
    };
    
    // Module definition
    
    static PyModuleDef
    moduledef = {
        PyModuleDef_HEAD_INIT,
        "countdict",
        MODULE_DOC,
        -1,
        NULL,       /* methods */
        NULL,
        NULL,       /* traverse */
        NULL,       /* clear */
        NULL
    };
    
    
    PyObject *
    PyInit_countdict(void)
    {
        PyObject * mod = PyModule_Create(&moduledef);
        if (mod == NULL) {
            return NULL;
        }
    
        CountDictType.tp_new = PyType_GenericNew;
        if (PyType_Ready(&CountDictType) < 0) {
            Py_DECREF(mod);
            return NULL;
        }
    
        Py_INCREF(&CountDictType);
        PyModule_AddObject(mod, "CountDict", (PyObject *)&CountDictType);
    
        return mod;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 292k
  • Answers 292k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I found the documentation to be mostly lacking myself. I… May 13, 2026 at 6:16 pm
  • Editorial Team
    Editorial Team added an answer Edited to take account of main post edits Html.RouteLink( "Looga",… May 13, 2026 at 6:16 pm
  • Editorial Team
    Editorial Team added an answer No. This is the entire reason for virtual functions. Without… May 13, 2026 at 6:16 pm

Related Questions

I have a question about how python treats the methods passed to sorted(). Consider
I have recently stumbled over a seeming inconsistency in Python's way of dealing with
Consider the following Python code: 30 url = http://www.google.com/search?hl=en&safe=off&q=Monkey 31 url_object = urllib.request.urlopen(url); 32
Consider the following Python exception: [...] f.extractall() File C:\Python26\lib\zipfile.py, line 935, in extractall self.extract(zipinfo,
Consider the following code: def CalcSomething(a): if CalcSomething._cache.has_key(a): return CalcSomething._cache[a] CalcSomething._cache[a] = ReallyCalc(a) return

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.