Python 2.7 Python:如何正确调用方法?
我有这门课:Python 2.7 Python:如何正确调用方法?,python-2.7,class,methods,scikit-learn,logistic-regression,Python 2.7,Class,Methods,Scikit Learn,Logistic Regression,我有这门课: class Tumor(object): """ Wrapper for the tumor data points. Attributes: idNum = ID number for the tumor (is unique) (int) malignant = label for this tumor (either 'M' for malignant or 'B' for b
class Tumor(object):
"""
Wrapper for the tumor data points.
Attributes:
idNum = ID number for the tumor (is unique) (int)
malignant = label for this tumor (either 'M' for malignant
or 'B' for benign) (string)
featureNames = names of all features used in this Tumor
instance (list of strings)
featureVals = values of all features used in this Tumor
instance, same order as featureNames (list of floats)
"""
def __init__(self, idNum, malignant, featureNames, featureVals):
self.idNum = idNum
self.label = malignant
self.featureNames = featureNames
self.featureVals = featureVals
def distance(self, other):
dist = 0.0
for i in range(len(self.featureVals)):
dist += abs(self.featureVals[i] - other.featureVals[i])**2
return dist**0.5
def getLabel(self):
return self.label
def getFeatures(self):
return self.featureVals
def getFeatureNames(self):
return self.featureNames
def __str__(self):
return str(self.idNum) + ', ' + str(self.label) + ', ' \
+ str(self.featureVals)
我试图在代码后面的另一个函数中使用它的一个实例:
def train_model(train_set):
"""
Trains a logistic regression model with the given dataset
train_set (list): list of data points of type Tumor
Returns a model of type sklearn.linear_model.LogisticRegression
fit to the training data
"""
tumor = Tumor()
features = tumor.getFeatures()
labels = tumor.getLabel()
log_reg = sklearn.linear_model.LogisticRegression(train_set)
model = log_reg.fit(features, labels)
return model
但是,当我测试代码时,我不断遇到此错误:
TypeError: __init__() takes exactly 5 arguments (1 given)
我知道在train_模型中创建肿瘤实例时,我没有使用这五个参数,但我如何才能这样做?到
\uuuuuu init\uuuu
的参数(或者\uu new\uuuuuu
,如果您正在使用该参数),可以预见的是,只需转到train_模型中创建实例的地方:
tumor = Tumor(idNum, malignant, featureNames, featureVals)
当然,实际上所有这些都需要值,因为它们都是必需的参数
但是,您不需要包含
self
,因为第一个参数会自动处理。到\uuuuuuuuuuuuuu
的参数(或者\uuuuuuu new\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
,如果您正在使用该参数),可以预见,只需转到在train\u模型中创建实例的地方:
tumor = Tumor(idNum, malignant, featureNames, featureVals)
当然,实际上所有这些都需要值,因为它们都是必需的参数
但是,您不需要包含
self
,因为第一个参数会自动处理。但是。。。在代码的其他地方调用带有参数的函数,而不询问如何。。。?用同样的方法tumor=tumor(1,2,3,4)
[编辑:哦,不清楚是不是调用类名触发了init方法!好的,我明白了。]好的,你有ID号、标签、功能名称和功能值来传递它吗?你的问题不是很清楚。init方法需要一些值,只有您知道在哪里可以找到它们(因为这是您的脚本)。。。在代码的其他地方调用带有参数的函数,而不询问如何。。。?用同样的方法tumor=tumor(1,2,3,4)
[编辑:哦,不清楚是不是调用类名触发了init方法!好的,我明白了。]好的,你有ID号、标签、功能名称和功能值来传递它吗?你的问题不是很清楚。init方法需要一些值,只有您知道在哪里可以找到它们(因为它是您的脚本)。