【问题标题】:Function inside class not being called类内的函数没有被调用
【发布时间】:2015-10-12 08:41:51
【问题描述】:

我有一个 python 类和几个函数,第一个调用第二个。但是, 2nd 永远不会被调用。 _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 {}

输出:

Now call method 2

只有第一个打印语句出来。

问题类似于Function Not getting called,但建议的解决方案似乎不适用于此。

【问题讨论】:

  • self this? self 作为_method2 的第一个参数在哪里?
  • 该代码应该会给您一个错误。您可以从错误消息中学到什么?
  • this._method2(context) 应该是 self.,因为你的 self 是实例的名称,而不是像 Javascript 中的这样。此外,您不需要以分号结束行。

标签: python function


【解决方案1】:
this._method2(context); ===>  self._method2(context)

this在python中不存在。你必须使用self。也不需要;。而是遵循适当的缩进。修改你的第二个函数为

def _method2(self, context={}):

【讨论】:

  • _method2 的签名缺少self。代码(就像现在一样)可以工作,但这是需要注意的另一件事。
  • 这是不同语言之间的杂耍问题。所以,我结束了使用this 而不是self。感谢您的提示。
【解决方案2】:

你的名字this没有定义,所以 Python 会抱怨。您可以更改您的第二个 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 {}

如果您想使用 实例通过_method1 调用_method2,您已创建,您必须在对引用实例的_methdo2() 的调用中再次提供self 参数,这是通过调用@987654332 上的函数隐式完成的_method1的@参数。

修改后的输出为:

In [27]: cls1 = call_methods()

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

P.S:声明类时不需要括号(),没有区别。你可能想看看 Python 2 中的New Style Classes

【讨论】:

  • 感谢您的解释。问题是使用this 而不是self。但是,python 从未因使用不存在的变量/对象而引发错误/异常/警告。它刚刚停止执行。
【解决方案3】:

应该是:

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

【讨论】:

    猜你喜欢
    • 2014-12-27
    • 2011-11-15
    • 1970-01-01
    • 2019-10-17
    • 2017-04-18
    • 2011-12-30
    • 2018-02-10
    • 1970-01-01
    相关资源
    最近更新 更多