在 Python 中在运行时为对象分配方法 [英] Assigning method to object at runtime in Python
问题描述
我正在尝试在 Python 中执行等效的 Javascript:
I'm trying to do the Javascript equivalent in Python:
a.new_func = function(arg1, arg2) {
var diff = arg1 - arg2;
return diff * diff;
}
现在,我这样做的方式是先定义方法,然后分配它,但我的问题是 Python 是否允许速记在同一行中进行分配和定义部分.像这样:
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
取而代之的是:
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 不支持这种语法.
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()
或者如果您希望该方法可以访问self
:
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()
这篇关于在 Python 中在运行时为对象分配方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!