Skip to content

Instantly share code, notes, and snippets.

@shun115
Created December 21, 2010 06:36
Show Gist options
  • Save shun115/749581 to your computer and use it in GitHub Desktop.
Save shun115/749581 to your computer and use it in GitHub Desktop.
Pythonの特殊メソッド
>>> class Test(object):
... a = ''
... def __new__(clazz, a): #インスタンス生成
... print 'new'
... #__new__はインスタンスではなくクラスを引数に取る(インスタンス生成前だから)
... #この__new__が呼び出されたコンテキスト内(clazz)で、Testクラスのスーパークラス呼び出し
... return super(Test, clazz).__new__(clazz) #object.__new__(clazz)と同義
... def __init__(self, a): #インスタンス生成後のコンストラクタ
... self.a = a
... print 'init'
... def __call__(self): #インスタンスに対する'呼び出し'
... print 'call'
... def p(self): #インスタンスメソッド
... print self.a
...
>>> a = Test(1)
new
init
>>> a.a
1
>>> a()
call
>>> a.p
<bound method Test.p of <__main__.Test object at 0x2b5256272f90>>
>>> a.p()
1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment