Reputation: 11
In Python it is valid to override a method, like:
class A():
def original(self):
print("original")
def alternative(self):
print("alternative")
A.original = alternative
a = A()
a.original()
which will print alternative
. But after transpilation to Javascript you'll get the error: Uncaught TypeError: Cannot set property original of function...
.
Of course this has to do with the fact that it is transpiled to:
var A = __class__ ('A', [object], {
__module__: __name__,
get original () {return __get__ (this, function (self) {
print ('original');
});}
});
where original
is a property which cannot be overriden in this way.
Is there a workaround for this? It can be useful in some cases to have this behaviour. Best regards
Upvotes: 1
Views: 90
Reputation: 7000
The following workaround will do the trick:
class A():
def original (self, anArg):
print ('Original:', anArg)
def alternative (self, anArg):
print ('Alternative:', anArg)
a0 = A ()
a0.original ('Time flies like an arrow.')
__pragma__ ('js', '{}', '''Object.defineProperty (A, "original", {
get: function (self) {return __get__ (this, alternative)}
})''')
a1 = A()
a1.original ('Fruit flies like a banana.')
It will print:
Original: Time flies like an arrow.
Alternative: Fruit flies like a banana.
I've added an argument to illustrate the generality of his solution.
Upvotes: 1