【问题标题】:Python: How to properly call a method?Python:如何正确调用方法?
【发布时间】:2016-09-02 17:56:18
【问题描述】:

我有这门课:

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_model 中创建 Tumor 实例时没有使用五个参数,但我该怎么做呢?

【问题讨论】:

  • 但是......您在代码中的其他地方调用带有参数的函数而不问如何......?做同样的事情。 tumor = Tumor(1,2,3,4) [编辑:哦,不清楚是对类名的调用触发了 init 方法!好的,我明白了。]
  • 嗯,你有ID号、标签、特征名称和特征值来传递吗?
  • 你的问题不是很清楚。 init 方法需要一些值,而您是唯一知道在哪里找到它们的人(因为它是您的脚本)。

标签: python-2.7 class methods scikit-learn logistic-regression


【解决方案1】:

__init__(或__new__,如果你正在使用它)的参数只需去你在 train_model 中创建实例的地方即可:

tumor = Tumor(idNum, malignant, featureNames, featureVals)

当然,您实际上需要所有这些值,因为它们都是必需的参数。

但是,您不需要包含 self,因为第一个参数会自动处理。

【讨论】:

    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 2020-07-28
    • 2021-01-15
    • 2015-06-30
    • 2021-09-03
    相关资源
    最近更新 更多