Created
December 21, 2010 06:36
-
-
Save shun115/749581 to your computer and use it in GitHub Desktop.
Pythonの特殊メソッド
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> 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