例えば:
>>> ctypes.c_char * 2
<type '_ctypes.SimpleType'>
型は のメソッドc_char_Array_2
によってオンザフライで作成されます ,それがどのように行われたか知りたいのですが、メソッドに関するソース コードが見つかりません。誰か助けてもらえますか?__mul__()
_ctypes._SimpleCData
__mul__()
のCソース実装を確認したい場合は、ここでctypes
見つけることができます。はCで実装されているため、どのファイルにも実装はありません。ctypes
__mul__
.py
Pythonでこのようなことを行うには、メタクラスを使用します。
簡単な例:
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
。)