Can I use my self variable as the method parameter such that I can achieve this:
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
I tried the following code but it gives me an error
class My_Class():
def __init__(self, arg1):
self.arg1 = arg1
def foo(self, x,y,z=self.arg1):
return (x+y)**z
NameError: name 'self' is not defined
2 Answers 2
The way that this might normally be done is to use None as the default parameter.
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
Comments
@2ps answer is excellent and is generally the accepted way to go. I just want to add that, if None is actually a valid argument to your function and you want to distinguish between None and "I didn't provide an argument", a little trick I've used in the past is to make my own private "none"-like object that no one else has access to.
_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.arg1in the parameter list like that.selfexists.