I'm trying to do the Javascript equivalent in Python:
a.new_func = function(arg1, arg2) {
var diff = arg1 - arg2;
return diff * diff;
}
Right now, the way I'm doing this is by defining the method first, and then assigning it, but my question is whether or not Python allows a shorthand to do the assigning and the defining part in the same line. Something like this:
a.new_func = def new_func(arg1, arg2):
diff = arg1 - arg2
return diff * diff
Instead of this:
def new_func(arg1, arg2):
diff = arg1 - arg2
return diff * diff
a.new_func = new_func
I realize the difference is not major, but am still interested to know whether or not it's possible.
Python supports no such syntax.
I suppose if you wanted, you could write a decorator. It might look a bit nicer:
def method_of(instance):
def method_adder(function):
setattr(instance, function.__name__, function)
return function
return method_adder
@method_of(a)
def new_func(arg1, arg2):
stuff()
Or if you want the method to have access to self
:
def method_of(instance):
def method_adder(function):
setattr(instance, function.__name__, function.__get__(instance))
return function
return method_adder
@method_of(a)
def new_func(self, arg1, arg2):
stuff()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With