我想将类方法作为默认参数传递给另一个类方法,以便我可以将该方法重用为@classmethod:
@classmethod
class foo:
def func1(self,x):
do somthing;
def func2(self, aFunc = self.func1):
# make some a call to afunc
afunc(4)
Run Code Online (Sandbox Code Playgroud)
这就是为什么在func2类aFunc默认情况下调用该方法的原因self.func1,但是我可以从类外部调用这个相同的函数,并在输入处传递一个不同的函数.
我明白了:
NameError:未定义名称"self"
这是我的设置:
class transmissionLine:
def electricalLength(self, l=l0, f=f0, gamma=self.propagationConstant, deg=False):
Run Code Online (Sandbox Code Playgroud)
但我希望能够electricalLength使用不同的函数调用gamma,例如:
transmissionLine().electricalLength (l, f, gamma=otherFunc)
Run Code Online (Sandbox Code Playgroud)
dou*_*lep 11
默认参数值在函数定义期间计算,而不是在函数调用期间计算.所以不,你不能.但是,您可以执行以下操作:
def func2(self, aFunc = None):
if aFunc is None:
aFunc = self.func1
...
Run Code Online (Sandbox Code Playgroud)