开发者

Python class is a subclass of itself, is this ok? Pitfalls?

I am wrapping a large C library using ctypes. ctypesgen generated the wrapping code (not too far开发者_Go百科 from how I do it myself). As a part of the ctypes wrapping C structures get made as objects, some of these have "setters" in C that would be handy to just subclass itself to use. What are the possible dangers here? Or this this fine to do as it seems to work but feels scary. Or is there a better way? I do not want to modify the ctypesgen generated python.

class some_struct(ctypes.Structure):
    _fields_ = [ ('a', ctypes.c_int), ('b', ctypes.c_double) ]

Then there is a c function set_some_struct_defaults() that I them implement this way:

class some_struct(some_struct):
     def __init__(self):
         set_some_struct_defaults(self)

So the idea is that the "new" some_struct has an init function that calls the C "setter" and so then when I initialize a python object I get all the defaults (which are of course a lot more complicated than this toy example):

val = some_struct.some_struct()

Observations I have had:

  • Order of the imports now matters, if you import some_struct from the wrapping.py and later from the class that extends it all is well, in the other order is an error. Not ideal.


You should do this simply by assigning some_struct a new __init__ function.

def new_init(self):
    self._old_init()
    set_some_struct_defaults(self)

some_struct.__dict__["_old_init"] = some_struct.__init__
some_struct.__init__ = new_init

This has the advantage that the original __init__ still gets called.


If you do this, it will overwrite the old class. If you don't plan on using the parent class, this will work fine. Of course, if you never use the old class to be gin with, it would be more efficient to just change the __init__ method of the original class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜