簡體   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