1

In ctypes documentation there is an example showcasing code on how to create arrays where an object of type class is multiplied by an int.

>>> from ctypes import *
>>> TenIntegers = c_int * 10
>>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> print(ii)
<c_long_Array_10 object at 0x...>

In python3 shell, I have checked and confirmed that ctypes.c_int is type class.

>>> type(ctypes.c_int)
<class '_ctypes.PyCSimpleType'>

I know that classes can define how operators behave with their class instances via dunder methods, but I have never seen definitions of behavior with the class objects themselves. I have tried checking the source code of ctypes, but I find it very difficult to understand it. Does anyone know how something like that could be implemented or how it is implemented?

OwenFlanders
  • 13
  • 1
  • 4

1 Answers1

0

This can be done with a metaclass, for example:

>>> class Meta(type):
...  def __mul__(self, other):
...   print(f"Multiplying {self} by {other}")  # Here you do something meaningful
...   return self  # As always, you can return whatever you please, not necessarily `self`
... 
>>> class SomeClass(metaclass=Meta):
...  ...
... 
>>> SomeClass * 10
Multiplying <class '__main__.SomeClass'> by 10
<class '__main__.SomeClass'>

As you correctly say, "classes can define how operators behave with their class instances via dunder methods". Any class is itself an instance of some metaclass (the metaclass of type is type itself), so the same principle holds with classes and metaclasses.

ForceBru
  • 43,482
  • 10
  • 63
  • 98