繁体   English   中英

如何将参数名称传递给函数的变量名称

[英]How to pass a name of an argument to the variable names of a function

我只是从#C开始进入python,遇到这个问题,我找不到答案,也许我无法正确地提出问题

我需要在使用时创建两个列表: load(positives)load(negatives) ,positives是文件的路径。 从#C开始,我习惯于使用这种结构,例如不再使用另一个变量再次复制相同的代码。 如果我需要5个清单怎么办。 使用此代码,我只能访问self.dictionary变量,而不能访问self.positives和self.negatives

我收到错误AttributeError:'Analyzer'对象在self.positives中的p行没有属性'positives':

主要问题是:如何使self.dictionary = []从参数名称创建列表变量-我稍后在代码中需要使用self.positives和self.negatives


def load(self, dictionary):

    i = 0
    self.dictionary = []
    with open(dictionary) as lines:
        for line in lines:
            #some more code
            self.dictionary.append(0)
            self.dictionary[i] = line
            i+=1

#later in code
    for p in self.positives:
        if text == p:
        score += 1
    for p in self.negatives:
        if text == p:
        score -= 1

#structure of a program:
class Analyzer():
    def load()
    def init()
         load(positives)
         load(negatives)
    def analyze()
        for p in self.positives

根据我对问题的了解,您正在尝试创建2个列表。 您首先必须这样声明它们:

FirstList = [ ]
SecondList = [ ]

然后,将要添加到列表中的任何值作为附加值,如下所示:

SecondList.append("The thing you want in the list")

在代码末尾,您的列表应填充您想要的内容。

您不能编写self.dictionary并期望python将其转换为self.positives或self.negatives。 代替正数,将self.positives和self.negatives插入函数并使用它们。

花了很长时间才弄清楚:

它要做的就是从load返回一个self.dictionary,并在init中将其分配为self.positives = self.load(positives):

#structure of a program:
class Analyzer():
def load()
    return self.dictionary
def init()
    self.positives = self.load(positives)
    self.negatives = self.load(negatives)
def analyze()
    for p in self.positives

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM