1

I have a python class and couple of functions, 1st calling 2nd. However, 2nd is never getting called. Also the line after _method2() invocation is never executed.

class call_methods():
    def _method1(self, context):
            print "Now call method 2";  
            this._method2(context);
            print "Finish"; 
            return {}

    def _method2(self, context={}):
            print "method 2 called"
            return {}

Output:

Now call method 2

Only 1st print statement comes out.

The question is similar to Function Not getting called but solution suggested there doesn't seem to apply to this.

Community
  • 1
  • 1
Mugoma J. Okomba
  • 3,185
  • 1
  • 26
  • 37

3 Answers3

1
this._method2(context); ===>  self._method2(context)

this does not exist in python.You have to use self.Also ; is not needed.Instead follow proper indentation.Modify your second function as

def _method2(self, context={}):
vks
  • 67,027
  • 10
  • 91
  • 124
1

You have the name this which is not defined, so Python will complain. You can alter your second method _method2() to take the argument self which, in Python, is a convention signifying the instance of a class you have created and want to reference:

class call_methods:
     def _method1(self, context):
         print "Now call Method 2"
         self._method2(context)
         print "finish"
         return {}

     def _method2(self, context={}):
         print "Method 2 Called"
         return {}

If you want to call _method2 via _method1 using the instance of a class you have created, you must again provide the self argument in the call to _methdo2() that references the instance, this is done implicitly by calling the function on the self argument of _method1.

Your output after altering will be:

In [27]: cls1 = call_methods()

In [28]: cls1._method1("con")
Now call Method 2
Method 2 Called
finish
Out[28]: {}

P.S: No need for parentheses () when declaring a class, it makes no difference. You might want to take a look at New Style Classes in Python 2

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • Thanks for the explanation. The problem was using `this` instead of `self`. However, python never threw a error/exception/warning for using a non-existing variable/object. It just stopped executing. – Mugoma J. Okomba Oct 12 '15 at 11:43
0

It should be:

    class call_methods():


    def _method1(self,context):

        print "Now call method 2";  

        this._method2(context);

        print "Finish"; 

        return {}


    def _method2(self, context={}):

        print "method 2 called"


        return {}
Nguyen Sy Thanh Son
  • 5,300
  • 1
  • 23
  • 33