I want to create a class that inherits from c_void_p and adds some behavior to it.
I need to inherit from it to support this "special" syntax: https://docs.python.org/3/library/ctypes.html#arrays.
When I create an array of MY_CLASS, it doesn’t seem to call any magic methods. Why is that, and what can I do about it?
from ctypes import c_void_p
class MY_CLASS(c_void_p):
def __init__(self, own: bool):
print("init called")
super().__init__()
self.own = own
def __new__(cls, *args, **kwargs):
print(f"new called with args={args}, kwargs={kwargs}")
return super().__new__(cls)
def __call__(self, own: bool):
print("call called")
self.own = own
def __del__(self):
print("del called")
if self.own:
# do something here one day
pass
def main():
print("Initialize MY_CLASS directly")
# This calls __new__, __init__, and __del__
MY_CLASS(False)
print("Initialize an array of MY_CLASS")
# This doesn’t call the __call__ method. Why?
# Also, it doesn’t call the __del__ method. Why?
my_array = (MY_CLASS * 5)(own=True)
if __name__ == "__main__":
main()