例如:
>>> ctypes.c_char * 2
<type '_ctypes.SimpleType'>
该类型c_char_Array_2
是由 中的__mul__()
方法动态创建的_ctypes._SimpleCData
,我想知道它是如何做到的,但是我找不到任何有关该__mul__()
方法的源代码,有人可以帮忙吗?
如果你想看看 C 源代码实现ctypes
,你可以在这里找到它。ctypes
是用 C 实现的,所以你不会__mul__
在任何.py
文件中找到 的实现。
在 python 中这样的事情可以使用metaclassing来完成。
简单的例子:
class Spam(type):
def spam(cls): print("spam:", cls.__name__)
def __mul__(self, other):
' create a new class on the fly and return it '
class Eggs(metaclass=Spam):
def eggs(self): print("eggs" * other)
return Eggs
class Ham(metaclass=Spam):
def ham(self): print('ham')
print(Ham) # <class '__main__.Eggs'>
Ham.spam() # spam: Ham
Ham().ham() # ham
# create new class:
TwoEggs = Ham * 2
print(TwoEggs) # <class '__main__.Eggs'>
TwoEggs.spam() # spam: Eggs
TwoEggs().eggs() # eggseggs
(pyhton3 语法,python2 使用__metaclass__
属性而不是metaclass
参数。)