LoginSignup
5
5

More than 5 years have passed since last update.

「 JS のメソッドの貸し借り (apply 使うやつ ) 」を Python でやるには

Posted at

前提、 JavaScript では

JavaScript では、 apply を通して、 function 内の this の文脈を変更することができることは有名。

言うなれば、他のクラスのメソッドを実行時に利用することができる。

ぐぐってみたところ、英語では borrowing method などと呼ばれてるようだ。文字通り「借りる」ということか。

function A () {
  this.value = 1;
}


function B () {
  this.value = 2;
}


B.prototype.show = function show () {
  console.log(this.value);
};


var a = A();
B.prototype.show.apply(a);  // まるで「 B のメソッドである show を a が借りて使ってる」よう
実行結果
1

本題、 Python で

今日、久しぶりにあった人と食事をしながら、「これを Python で同じことができるか?」という話になった。
Python だと self を実行時に変えたい。結論から言うと「できる」。
その場では説明できなかったので、 Qiita に書くことにした。

Pythonで
class A(object):

    def __init__(self):
        self.value = 1


class B(object):

    def __init__(self):
        self.value = 2

    def show(self):
        print(self.value)


a = A()
B.__dict__['show'](a)
実行結果
1

まとめ

Python では __dict__ を通していろいろ参照できるという話でした。

ただ、これを使いすぎると黒魔術になるので、普段使いはやめましょう。

5
5
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
5
5