Issue
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
Solution
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)
I've also changed the class name to upper camelcase to follow the typical style.
This will allow you to call the functions without an instance, for example print(Parser.bar('test'))
will print test
.
Answered By - shayaan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.