我可以将类方法作为默认参数传递给另一个类方法吗 [英] Can I pass class method as and a default argument to another class method
问题描述
我想将类方法和默认参数传递给另一个类方法,以便可以将该方法作为 @classmethod
:
I want to pass class method as and a default argument to another class method, so that I can reuse the method as a @classmethod
:
@classmethod
class foo:
def func1(self,x):
do somthing;
def func2(self, aFunc = self.func1):
# make some a call to afunc
afunc(4)
这就是为什么在类 aFunc $ c中调用方法
func2
的原因$ c>默认为 self.func1
,但我可以从类外部调用此函数,并在输入时将其传递给其他函数。
This is why when the method func2
is called within the class aFunc
defaults to self.func1
, but I can call this same function from outside of the class and pass it a different function at the input.
我得到:
NameError:名称'self'未定义
NameError: name 'self' is not defined
这是我的设置:
class transmissionLine:
def electricalLength(self, l=l0, f=f0, gamma=self.propagationConstant, deg=False):
但是我希望能够调用具有不同功能的 electricalLength
,例如:
But I want to be able to call electricalLength
with a different function for gamma, like:
transmissionLine().electricalLength (l, f, gamma=otherFunc)
推荐答案
默认参数值是在函数定义期间计算的,而不是在函数调用期间计算的。所以不,你不能。但是,您可以执行以下操作:
Default argument values are computed during function definition, not during function call. So no, you can't. You can do the following, however:
def func2(self, aFunc = None):
if aFunc is None:
aFunc = self.func1
...
这篇关于我可以将类方法作为默认参数传递给另一个类方法吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!