我想的方法来接受另一种方法的结果作为参数方法的结果:传递作为参数传递给其他方法
def method2(self, self.method1(arg_for_method_1))
pass
,但我不断收到错误
NameError: name 'self' is not defined
为什么?
我想的方法来接受另一种方法的结果作为参数方法的结果:传递作为参数传递给其他方法
def method2(self, self.method1(arg_for_method_1))
pass
,但我不断收到错误
NameError: name 'self' is not defined
为什么?
您试图提供一个值,其中Python期望一个简单的名称;该名称将在运行时分配一个值。
由于self
已经是一个说法,你可能只需要调用self.method1()
时method2
运行:
def method2(self)
x = self.method1()
如果你想为一个参数被method1
设置的默认值,使用None
作为默认值。
def method2(self, var=None):
if var is None:
var = self.method1()
默认参数非常有用。 – JAB
class XYZ:
def some_method(self):
return math.PI
def method1(self,x):
return x**0.5
def method2(self, method1):# <- this is the argument ... not the value
print method1()
def method3(self,some_value):
print some_value
x = XYZ()
x.method2(x.some_method)
x.method3(x.method1(5)) #<--- you call the method when you pass it not when you define it
但方法1有一个可选的参数,我将澄清原文。 – user1654183
它有一个参数... –
请记住,您请求的参数是*输入*到您的函数。调用一个请求它作为输入时要求的方法看起来不太一致,因此在定义中不允许。幸运的是,将该逻辑放在定义的主体中是完全允许的! (这忽略了可选参数) – BlackVegetable