我想从同类中的另一个python文件中导入函数



我试图这样导入:
sample_wave是另一个python文件onListener是className,on -onpartialtranscript在it

中函数
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()  

您不能从类导入函数,应该导入类,然后创建该类的对象并调用该方法

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

您无法直接导入函数。但是,您可以:

  1. 如先前的答案中所述,导入类并实例化对象
  2. 重写功能
  3. 导入班级并创建自己的孩子,覆盖__init__方法

我会投票给3.,这对我来说似乎是最干净的。此外,您还可以尝试进行实验。然而,它可以引入意外的结果,评估的使用不是一个好实践,例如。

test.py-您要从:

导入的模块
class onlistener:
    def __init__(self):
        pass
    def testfunction(self):
        print "Imported"

在以下内容中,使用Inspect Module查找称为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)

最新更新