在ctypes documentation中,有一个示例代码演示如何创建数组,其中将类类型的对象乘以一个整数。
>>> 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...>
在python3 shell中,我已经检查并确认ctypes.c_int是类型类。
>>> type(ctypes.c_int)
<class '_ctypes.PyCSimpleType'>
我知道类可以通过dunder方法定义运算符如何处理其类实例,但是我从未见过有关类对象本身的行为定义。我尝试检查ctypes的源代码,但是我很难理解它。有谁知道这样的事情如何实现或如何实现?
例如,可以用metaclass完成:
>>> 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'>
正如您正确地说的那样,“类可以通过dunder方法定义操作符如何处理其类实例”。任何类本身都是某些元类的实例(type
的元类是type
本身),因此类和元类的原理相同。