0

I have a function in a class that needs to be called several times in various other functions. It also has to be called independently. I'm getting this error: NameError: name 'function_i_use_often_within_others' is not defined

Is there a way a function can inherit other functions without having to nest them in each function that needs that action? See the sample code below. I tried creating a separate class and having it inherit the methods.. It still faced the same problem.

class testcase:
    def __init__(self,xpath):
        self.xpath = xpath

    def function_i_use_often_within_others(self):
        print('DOING SOMETHING OFTEN')
    
    def function2(self):
        function_i_use_often_within_others()
        print("Function2 doing something else")

    def function3(self):
        function_i_use_often_within_others()
        print("Function3 doing something else")
         

trial = testcase('This is xpath')
trial.function_i_use_often_within_others()
trial.function2()
trial.function3()
John Carr
  • 69
  • 3
  • 1
    Your edit cleared up *some* of my questions, but I'm still not certain I understand what you're trying to do and why your solution doesn't work? Is there something wrong? – ddejohn Jun 18 '22 at 18:49
  • 1
    Calling a function from within another function isn't really "duplicate" code. Have you looked into decorators? Since your example code is so vague, I'm not certain they'd be applicable, but it sounds kind of like you'd maybe want to decorate your instance methods. – ddejohn Jun 18 '22 at 18:51
  • What you have written there seems like the best plan. Inheritance is a cool trick, but it hides necessary information from the reader. – Tim Roberts Jun 18 '22 at 18:51
  • OP, if you can provide a minimal concrete example, it may help clear up whether a decorator could be applicable here. – ddejohn Jun 18 '22 at 19:04
  • I updated it.. the code above gets this error NameError: name 'function_i_use_often_within_others' is not defined. Sorry for not posting the full problem originally and thank you all for your help. Still wondering how to do this. – John Carr Jun 20 '22 at 19:38
  • @JohnCarr so you are asking how to *call a method from another method*. I linked to a duplicate which addresses your problem - you aren't using `self`. I also suggest you read the [official tutorial on writing class definitions](https://docs.python.org/3/tutorial/classes.html). The fact that you need to use `self` to access member data is a pretty basic concept that should be covered in any basic tutorial, although, it might not be obvious is you are coming from, say, Java where you can implicitly reference the instance due to the scoping rules – juanpa.arrivillaga Jun 20 '22 at 19:40

0 Answers0