1

I want to create a class that includes two functions where one of them calls the other one, for example:

class Parser:

    def foo(a):
        return a
 
    def bar(b):
        return foo(b * 2)

This errors out with:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in bar
NameError: name 'foo' is not defined
4
  • Either you use self.foo1(a) or you mixed the vars and you want to return foo2(a). You should read about Classes
    – Saelyth
    Nov 15, 2017 at 11:22
  • both not works. Nov 15, 2017 at 11:23
  • Please show the code where you are calling foo2().
    – cdarke
    Nov 15, 2017 at 11:32
  • The error thrown already in class, not in using the class from outside. Nov 15, 2017 at 11:34

1 Answer 1

7

You either forgot to have self as one of the parameters, or forgot to set the methods to be static with @staticmethod.

If you'd like the methods to be instance methods use self:

class Parser:

    def __init__(self):
        pass

    def foo(self, a):
           return a

    def bar(self, a):
           return self.bar(a)

You will then have to create an instance of the parser and call bar on this instance, for example:

parser = Parser()
print(parser.bar('test'))

If you'd like the methods to be static, you'll need to change your class to the following for the static method:

class Parser:
    @staticmethod
    def foo(a):
        return a

    @staticmethod
    def bar(a):
        return Parser.foo(a)

This will allow you to call the functions without an instance.

print(Parser.bar('test'))
1
  • 3
    +1 for listing both the "static" and "instance" way, although I'm pretty sure the latter is what OP wanted. To top that off one could make the staticmethod foo2 a classmethod, which avoids the explicit reference to Parser.
    – Jeronimo
    Nov 15, 2017 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.