【问题标题】:How to pass a name of an argument to the variable names of a function如何将参数名称传递给函数的变量名称
【发布时间】:2017-06-21 07:51:09
【问题描述】:

我只是从#C 开始接触 python,我有一个我无法找到答案的问题,也许我无法正确地形成一个问题

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

我收到错误 AttributeError: 'Analyzer' object has no attribute 'positives' at line 'for p in self.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

【问题讨论】:

  • 您是否将load 定义为类外的方法或函数?我怀疑是后者。
  • 我不明白你的问题。你的代码到底是怎么不工作的?
  • 什么是字典?它持有什么样的价值观?
  • 字典参数得到肯定和否定 - 它保存文件的路径,所以我猜是一个字符串

标签: python list variables arguments names


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    花了很长时间才弄明白:

    只需从 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
    

    【讨论】:

      【解决方案3】:

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

      FirstList = [ ]
      SecondList = [ ]
      

      然后取你想要添加到列表中的任何值并像这样附加它:

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

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

      【讨论】: