2017-03-06 70 views
0

我試圖導入像這裏面導入功能:
sample_wave是另一個Python文件onlistener是類名和onpartialTranscript是功能它我想從另一個Python文件,該文件是類

from sample_wave import onPartialTranscript 

我如何從另一個文件調用類內的函數?

def create_username(): 
    username, pwd 
    try: 
     engine.say("Enter the user name and password for New user") 
     engine.runAndWait() 
     username = add_user(raw_input(onPartialTranscript(username), pwd=getpass.getpass())) 
     engine.say("User Credentials added! %s" % username) 
     engine.runAndWait() 
    except Exception as e: 
     engine.say("recheck credentials") 
     engine.runAndWait() 

回答

0

您不能導入從類,你應該導入類,然後創建該類的對象,並調用該方法

from sample_wave import onlistener 
x = onlistener(); 
username = ... 
x.onPartialTranscript(username) 
+0

還是我對着導入錯誤的從sample_wave進口onlistener –

+0

什麼樣的錯誤你是從sample_wave進口面臨 –

+0

onListener 導入錯誤:CA沒有進口名稱onListener在python2.7 –

0

您不能直接導入功能功能。但是,您可以:

  1. 導入類和實例化對象,如早期的答案
  2. 表示重寫功能
  3. 導入類,並創建自己的作爲其子,覆蓋__init__方法

我會投3票,對我來說似乎是最乾淨的。 除了你可以嘗試下面的實驗。然而,可以引入意想不到的效果,EVAL的使用不是例如一個很好的做法,等

test.py - 這要從導入模塊:

class onlistener: 
    def __init__(self): 
     pass 

    def testfunction(self): 
     print "Imported" 

在下文中,使用檢查模塊發現的函數調用testfunction:

import inspect 
from test import onlistener 

def main(): 
    classfunc = inspect.getsourcelines(onlistener.testfunction) 

    # the first field contains the code (list of lines), convert it to string 
    my_str = '' 
    first = True 

    for line in myfunc[0]: 
     if first: 
      # First line contains 'self' argument, remove it 
      line = line.replace('self', '') 
      first = False 

     # we need to remove the indentation, here it's 4 spaces 
     my_str += line[4:] 

     # append the call to the function 
     # newline is needed due to specification of compile function 
     my_str += 'testfunction()\n' 

     # create code object 
     my_func = compile(my_str, '<string>', 'exec') 

     # The last line will call the function and print "Imported" 
     eval(my_func)