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.
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;