In JavaScript, it is well known that you can change the context of this
in function through apply
.
So to speak, methods of other classes can be used at runtime.
After going around, it seems that it is called the borrowing method in English. Does it literally mean "borrow"?
Example
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); //It's like "a borrows and uses show, which is a method of B."
Execution result
1
Today, while eating with someone I hadn't seen in a long time, I was asked, "Can I do the same with Python?" In Python I want to change `` `self``` at runtime. From the conclusion, "I can". I couldn't explain it on the spot, so I decided to write it in Qiita.
In 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)
Execution result
1
It was said that in Python you can refer to various things through __dict__
.
However, if you use this too much, it will become black magic, so stop using it normally.
Recommended Posts