[英]Importing another class into a class python
I would like to be able to import class A into class B and use the functions present in class B. Something like the following:我希望能够将 A 类导入 B 类并使用 B 类中存在的函数。如下所示:
from scipy import stats
import numpy as np
class TestLearner(object):
def __init__(self, param1 = 2):
self.param = param1
def train_model(self, X, y):
slope, intercept, r_value, p_value, std_err = stats.linregress(X,y)
self.slope = slope
self.intercept = intercept
def predict_new(self, X):
y = self.intercept + self.slope * X
return y
class Test(object):
def __init__(self, learner):
self.learner = learner
def add_evidence(self, X, y):
learner = self.learner
slope, intercept = learner.train_model(X,y)
self.slope = slope
self.intercept = intercept
def predict(self, X):
y= self.intercept * self.slope * X
return y
import TestLearner as t将 TestLearner 导入为 t
x_train = np.random.randn(10,3)
y_train = np.random.randn(10,)
x_test = np.random.randn(5,3)
testing = Test(learner = t.TestLearner)
testing.add_evidence(X=x_train,y= y_train)
I get the following error:我收到以下错误:
Traceback (most recent call last):
File "<input>", line 40, in <module>
File "<input>", line 26, in add_evidence
TypeError: train_model() missing 1 required positional argument: 'y'
Which I don't understand.我不明白。 It seems that the train model is looking for "self" as an input and I thought that was self contained in the TestLearner class?似乎火车模型正在寻找“自我”作为输入,我认为它包含在 TestLearner 类中?
In order to call a method within a class , you need to initilize that class into an instance ,you can initialize your instance in the Test constructor , but this only works if you pass into Test() another class and not an instance为了调用类中的方法,您需要将该类初始化为一个实例,您可以在 Test 构造函数中初始化您的实例,但这仅在您传入 Test() 另一个类而不是实例时才有效
class Test(object):
def __init__(self, learner):
self.learner = learner()
def add_evidence(self, X, y):
learner = self.learner
slope, intercept = learner.train_model(X,y)
self.slope = slope
self.intercept = intercept
def predict(self, X):
y= self.intercept * self.slope * X
return y
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.