Python - 从另一个函数调用类实例函数?

时间:2015-02-18 21:38:39

标签: python function class

是的,我知道即使这个问题的标题也令人困惑。对不起,但这是我能描述的最好的事情。

所以......我还在学习使用Python类。这是我需要帮助的一个。基本上我有一个类,我用它创建一个秒表。然后我在该类之外有一堆执行其他任务的函数,我有我的Main函数。我需要能够从一个非类函数启动和停止我的stopwath类实例。这是一个精简的版本,所以你可以看到我的结构。

class StopWatch(Frame):
     ...
         def Start(self):
              ...              
         def Start(self):
              ...
def dosomething():
             # right here I want to call the sw1.Start function in StopWatch.  
def dosomethingelse();
             # right here I want to call the sw1.Stop function in StopWatch.
def main():
          sw1 = StopWatch(root)

我试图做这样的事情,但它没有用。

class StopWatch(Frame):
     ...
         def Start(self):
              ...              
         def Start(self):
              ...
def dosomething():
             # right here I want to call the sw1.Start function in StopWatch.  
             tmp = StopWatch
             tmp.Start()   
def dosomethingelse();
             # right here I want to call the sw1.Stop function in StopWatch.
             tmp = StopWatch
             tmp.Start() 
def main():
          sw1 = StopWatch(root)

我确信这不起作用,因为我不是StopWatch类的sw1实例。

那么如何调用StopWatch类的Start和Stop函数,例如sw1?

1 个答案:

答案 0 :(得分:2)

很明显,你还没有掌握Python functionsScope的概念。所以我将引导您完成它,但是请阅读更多教程!

您正在sw1范围中定义变量StopWatchmain()类的实例。它无法在main()之外的任何地方访问。因此,您需要在方法之间传递对象。我完成了dosomething()dosomethingelse()方法的参数,如下所示:

 def doSomething(stopwatch):
     # whatever comes first
     stopwatch.start()


 def doSomethingElse(stopwatch):
     # whatever comes first
     stopwatch.stop()

然后你只需调用这些方法并传递它们sw1,就像这样:

def main():
    sw1 = StopWatch(root)
    doSomething(sw1)
    doSomethingElse(sw1)
相关问题