Python:如何正确调用方法?

Posted

技术标签:

【中文标题】Python:如何正确调用方法?【英文标题】:Python: How to properly call a method? 【发布时间】: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 方法需要一些值,而您是唯一知道在哪里找到它们的人(因为它是您的脚本)。 【参考方案1】:

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

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

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

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

【讨论】:

以上是关于Python:如何正确调用方法?的主要内容,如果未能解决你的问题,请参考以下文章

终止python程序的正确方法,无论调用位置如何,并进行清理

类中的Python调用方法

Python进阶-继承中的MRO与super

如何正确调用 Parallel.ForEach 循环中的调用异步方法[重复]

Python全栈day21(调用模块路径BASEDIR的正确方法)

如何让 CRON 调用正确的路径