Drkcore

19 01 2011 Python Tweet

Pythonのクラスシステムはどうなっているのか

#expertpython エキスパートPythonプログラミング読書会05

エキスパートPython 3.5.2

class MyClass(object):
    def mymethod(self):
        return "hello world"

これは

>>> def method(self): return "hello world"
... 
>>> klass = type('MyClass', (object,), {'mymethod':method})
>>> ins = klass()
>>> ins.mymethod()
'hello world'

__metaclass__はtypeが読み出される前後に様々な処理を挟み込むことができる

ProductName エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス / 3780円 ( 2010-05-28 )


一度理解してしまえば分かりやすい

11.01.18追記

もちろんlamda式を使ってもいいわけだ

>>> klass = type('MyClass', (object,), {'mymethod': lambda self: 'hello world'})
>>> ins = klass()
>>> ins.mymethod()
'hello world'

About

  • もう5年目(wishlistありマス♡)
  • 最近はPythonとDeepLearning
  • 日本酒自粛中
  • ドラムンベースからミニマルまで
  • ポケモンGOゆるめ

Tag

Python Deep Learning javascript chemoinformatics Emacs sake and more...

Ad

© kzfm 2003-2021