如何从另一个python文件运行函数

问题描述

我有一个.py:

   Class Boxfinitestatemachine(models):
   ..... 
       @transistion...
       def hello(self):
           Print happy
       ....
       @transostion..
       def bye(self):
           Print sad
        ....

通常情况下,运行方式为:在外壳窗口中按F5并输入以下命令:

        >>>State= Boxfinitestatemachine()      #input
        >>> State.hello() #input
        >>> happy         #output
        >>> State.bye()  # input
        >>> Sad           #output

现在我有了另一个文件b.py,其中包含FOR循环功能如下:

         For I in range 2:

现在我需要,如果I == 0,则必须执行state.hello并打印出来。

类似地,对于I == 1,应执行state.bye并打印Sad。

如何执行此要求。任何帮助。

解决方法

您可以在文件b上导入boxfinboxfinitestatemachine,并像在终端上一样使用。

from fileA import boxfinboxfinitestatemachine

State = boxfinboxfinitestatemachine()
for i in range 2:
  if(i == 0):
    State.hello()
  if(i == 1):
    State.bye()