使用自变量作为python方法参数
我是否可以使用我的自变量作为方法参数,以便实现以下目标:使用自变量作为python方法参数,python,python-3.x,Python,Python 3.x,我是否可以使用我的自变量作为方法参数,以便实现以下目标: myclass = My_Class(arg1=3) output = myclass(1,2) # If the third argument is not given, use the self.arg1 variable output = myclass(1,2,10) # If the third argument is given, use it instead of self.arg1 我尝试了以下代码,但它给了我一个错误
myclass = My_Class(arg1=3)
output = myclass(1,2) # If the third argument is not given, use the self.arg1 variable
output = myclass(1,2,10) # If the third argument is given, use it instead of self.arg1
我尝试了以下代码,但它给了我一个错误
class My_Class():
def __init__(self, arg1):
self.arg1 = arg1
def foo(self, x,y,z=self.arg1):
return (x+y)**z
NameError:未定义名称“self”
通常的做法是使用
None
作为默认参数
class My_Class():
def __init__(self, arg1):
self.arg1 = arg1
def foo(self, x, y, z=None):
if z is None:
z = self.arg1
return (x+y)**z
@2ps答案非常好,通常是公认的方式。我只想补充一点,如果
None
实际上是函数的一个有效参数,并且您想区分None
和“我没有提供参数”,那么我过去使用的一个小技巧就是创建我自己的私有“None”——类似于对象,其他人无权访问
_no_arg = object()
class My_Class():
def __init__(self, arg1):
self.arg1 = arg1
def foo(self, x, y, z=_no_arg):
if z is _no_arg:
z = self.arg1
return (x+y)**z
您不能在参数列表中这样引用
self.arg1
。默认值在类初始化时仅计算一次。此时,没有类的实例,因此不存在self
。