Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带有模块全局变量的python模块_Python_Module_Global Variables_Python Import - Fatal编程技术网

带有模块全局变量的python模块

带有模块全局变量的python模块,python,module,global-variables,python-import,Python,Module,Global Variables,Python Import,我制作了一个包含多个函数的python文件,我想将其用作一个模块。假设这个文件名为mymod.py。其中包含以下代码 from nltk.stem.porter import PorterStemmer porter = PorterStemmer() def tokenizer_porter(text):

我制作了一个包含多个函数的python文件,我想将其用作一个模块。假设这个文件名为mymod.py。其中包含以下代码

from nltk.stem.porter import PorterStemmer                      
porter = PorterStemmer()  

def tokenizer_porter(text):                                                                                    
    return [porter.stem(word) for word in text.split()]  
然后我尝试将其导入iPython并使用tokenizer_porter:

from mymod import * 
tokenizer_porter('this is test')
生成了以下错误

TypeError: unbound method stem() must be called with PorterStemmer instance as first argument (got str instance instead)
我不想把porter放在tokenizer\u porter函数中,因为它感觉是多余的。这样做的正确方式是什么?还有,有没有可能避免

from mymod import * 
在这种情况下


非常感谢

要在python中访问全局变量,您需要在function中使用
global
关键字指定它

def tokenizer_porter(text):     
    global porter                                                                           
    return [porter.stem(word) for word in text.split()]  

它对我有用。谢谢在这种情况下,是否可以避免mymod导入*?我从mymod import tokenizer\u porter尝试过,但没有成功。在添加了global之后,您尝试过吗?因为它应该起作用