13
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】特定のインスタンスにメソッドを追加

Posted at

types.MethodTypeを使う

types.MethodType(function, instance)

Create a bound instance method object.

バウンドされたインスタンスメソッドを作成します

動作環境

Python 3.7.1

特定のインスタンスにだけメソッドを追加する

class MyClass:
    def __init__(self, name):
        self._name = name


a = MyClass('tamago')
b = MyClass('taro')

bのインスタンスにだけメソッドを追加したい場合、types.MethodType()bに紐づくインスタンスメソッド(get_name)を生成し、b.get_nameに設定する

# 関数を定義
>>> def get_name(self):
...     return self._name

>>> import types
# bのインスタンスメソッドを生成し、設定する
>>> b.get_name = types.MethodType(get_name, b)

>>> b.get_name()
'taro'

また、aにはget_nameというメソッドは無いため、エラーになる

>>> a.get_name()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyClass' object has no attribute 'get_name'

'MyClass' object has no attribute 'get_name'

面白い

参考文献

13
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?