Reputation: 6328
I am trying to pass a function, which doesn't take any input and returns some value. The function is defined inside the class. However, it is throwing following error:
NameError: name 'self' is not defined
Please see the sample code below:
class Test():
def rand(self):
return 4
def print_rand(self, num=self.rand()):
print num
t = Test()
print t.print_rand()
Any workaround, please? Note that I am using Python 2.7 in on Ubuntu 14.04 LTS PC.
Upvotes: 0
Views: 67
Reputation: 230
If you have to define num
as a method then what @Shadow said is the best way to go, unless num
can also be passed a value of None
.
Another option is simply defining a function that doesn't take a self, and just calling it in your params as a normal function.
class Test():
def rand():
return 4
def print_rand(self, num=rand()):
print num
t = Test()
print t.print_rand()
If you actually intend on not accessing anything within the instance, and will be returning some constant value, you could define it as a @staticmethod.
That all being said, I am not sure what the use case is for calling a method to get a default value right within the function parameter declaration. It's better to explicit like @Shadow's post said for something that's uncommon. It'll save you and someone else some good time in the future.
Upvotes: 1
Reputation: 810
It's not possible using self as your optional argument but defining static properties would work.
https://repl.it/@marksman/ravijoshi
class Test(object):
rand = 4 # statically defined
def print_rand(self, num=rand):
print(num)
t = Test()
t.print_rand()
Upvotes: 3
Reputation: 9427
You can't do it that way.
And that's a good thing - because the default is evaluated at function creation (ie, not when it's called). If it did happen to work, then the random number would have been generated when the program first loads this function, and then kept the same random number for every call afterwards.
This should give you the effect you want though;
def print_rand(self, num=None):
if num is None:
num = self.rand()
# ...
Upvotes: 3