0

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

asked Oct 31, 2020 at 3:44
2
  • 1
    You can't refer to self.arg1 in the parameter list like that. Commented Oct 31, 2020 at 3:48
  • 1
    The default value is evaluated only once at class initialization time. At this point no instance of the class and therefore no self exists. Commented Oct 31, 2020 at 3:49

2 Answers 2

4

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
answered Oct 31, 2020 at 3:46
Sign up to request clarification or add additional context in comments.

Comments

2

@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
answered Oct 31, 2020 at 3:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.