0

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.

1
  • You can't use self.rand() Commented Nov 17, 2017 at 3:53

3 Answers 3

3

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()
    # ...
Sign up to request clarification or add additional context in comments.

Comments

3

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()

Comments

1

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.

1 Comment

If you do this then you won't be able to call rand from the instance as python will attempt to pass in self.

Your Answer

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.