简体   繁体   English

类内的函数未调用

[英]Function inside class not being called

I have a python class and couple of functions, 1st calling 2nd. 我有一个python类和几个函数,第一次调用第二次。 However, 2nd is never getting called. 但是,2nd永远不会被调用。 Also the line after _method2() invocation is never executed. _method2()调用之后的行也不会执行。

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. 问题类似于“ 功能未调用”,但建议的解决方案似乎不适用于此功能。

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

this does not exist in python.You have to use self .Also ; this不python.You存在必须使用self 。还有; is not needed.Instead follow proper indentation.Modify your second function as 不需要,而是遵循适当的缩进。将第二个函数修改为

def _method2(self, context={}):

You have the name this which is not defined , so Python will complain. 您有未定义的名称this ,因此Python会抱怨。 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: 您可以更改第二个method _method2()来接受参数self ,这在Python中是一种约定,表示已创建并要引用的类的instance

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 . 如果要使用已创建的实例通过_method1调用_method2 ,则必须再次在引用该实例的_methdo2()的调用中提供self参数,这是通过在函数的self参数上调用函数来隐式完成的_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]: {}

PS: No need for parentheses () when declaring a class, it makes no difference. PS:声明类时不需要括号() ,没有区别。 You might want to take a look at New Style Classes in Python 2 您可能想看看Python 2中的New Style Classs

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 {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM