[英]python: call a class from a script in a different directory and get function
I have a script that I am currently working on, named exp1.py and it's located in我有一个当前正在处理的脚本,名为exp1.py ,它位于
/project/exp1.py
In this script, I am trying to call a function named computelikelihood() , which is inside the class Class() , which is in script method.py , in a different directory:在这个脚本中,我试图调用一个名为computelikelihood()的函数,该函数位于Class()类中,该类位于脚本method.py 中,位于另一个目录中:
/project/methods/c_CLASS/method.py
So, in my code in exp1.py , I do this:所以,在我的exp1.py代码中,我这样做:
import sys
sys.path.append('/project/methods/c_CLASS/')
Which gets me to the folder where method.py is located, but when I want to call the Class()
from the method.py , so that I get the function computelikelihood() , that I actually want, I get error.这让我到method.py所在的文件夹,但是当我要调用的Class()
从method.py,所以我得到的功能computelikelihood(),其实我是想,我得到的错误。 I try this:我试试这个:
from method import Class
from Class import computelikelihood
But I get ImportError: No module named Class
.但我得到ImportError: No module named Class
。 Can anyone help?任何人都可以帮忙吗?
EDIT This is how the __init__
of my Class
looks like:编辑这是我的Class
的__init__
的样子:
class Class:
def __init__(self,e2wl,w2el,label_set):
self.e2wl = e2wl
self.w2el = w2el
self.workers = self.w2el.keys()
self.examples = self.e2wl.keys()
self.label_set = label_set
Since you are trying to use a method from a Class, you should do so via the class.由于您正在尝试使用类中的方法,因此您应该通过类来使用。 Do not import the function alone as it isn't intended to be used as such:不要单独导入该函数,因为它不打算这样使用:
from method import Class
Class.computelikelihood()
However, this only works if computelikelihood
is a static/class method:但是,这仅在计算computelikelihood
是静态/类方法时才有效:
class Class:
@classmethod
def computelikelihood(cls):
...
# or
@staticmethod
def computelikelihood():
...
If it's an instance method:如果是实例方法:
class Class:
def computelikelihood(self):
...
You'll need to first instantiate an object of class Class
:您需要首先实例化Class
的对象:
from method import Class
classObject = Class()
classObject.computelikelihood()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.