Created
March 14, 2017 14:42
-
-
Save iwiwi/9a7f5985e2be0be35e8c18360294e2f1 to your computer and use it in GitHub Desktop.
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 A: | |
... def hello(self): | |
... print('hellooooo') | |
... def __len__(self): | |
... print('lennnnnn') | |
... return 10 | |
... def __call__(self): | |
... print('calllllled') | |
... | |
>>> a = A() | |
>>> a.hello() # 当たり前に呼べる | |
hellooooo | |
>>> len(a) # 当たり前に呼べる | |
lennnnnn | |
10 | |
>>> a() # 当たり前に呼べる | |
calllllled | |
# インスタンスにメンバとして挿そうとしてみる場合 | |
>>> class B: | |
... pass | |
... | |
>>> b = B() | |
>>> b.hello = lambda: print('hello') # hello を挿してる | |
>>> b.__len__ = lambda: 10 # __len__ を挿してる | |
>>> b.__call__ = lambda: print('calllllled') # __call__ を挿してる | |
>>> b.hello() # 呼べる | |
hello | |
>>> len(b) # 呼べない!! | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
TypeError: object of type 'B' has no len() | |
>>> b() # 呼べない!! | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
TypeError: 'B' object is not callable |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment