读取文件,获取文件行内容,然后将内容用作 class 方法定义 Python 的参数

reading a file, taking file line content, then using content as parameters for class method definitions Python

我在这里要做的是读取文件的一行。如果文件中的内容符合正确的条件,则执行我的 class 中的定义之一。问题是我不知道我需要什么样的代码。

这是我目前的情况:

class Score:
# class to hold a running score, from object to parameter
# also to set number of scores that contribute to total of 1

    def __init__(self):
#initalizes the running score and score input accumilators
        self.runScore = 0
        self.scoreInputs = 0

    def updateOne (self, amount):
#updates running score by amount and Score input by 1
        self.runScore += amount
        self.scoreInputs += 1

    def updateMany(self,lst):
#updates running score by the sum of the list and score inputs by the amount of
# number of items in the list
        self.runScore += sum(lst)
        self.scoreInputs += len(lst)

    def get(self):
#returns the current score based on total amount scored
        print(self.runScore)

    def average(self):
#returns the average of the scores that have contributed to the total socre
        print(self.runScore // self.scoreInputs)

def processScores (file):
    with open('file','r') as f:
    for line in f:
        line

想法是 processScores 将为 运行。当代码逐行读取文件时,如果它在行示例 G 中找到一个 certian 标记,那么它读取的下一行应输入到 def updateOne 中。但这只是一个例子。

关于我可以做得更好的任何想法?

谢谢

你想要这样的东西:

myScore = Score()

def processScores (file):
    with open('file','r') as f:
        sw = False
        for line in f:
            if sw == True:
                am = int(line[0])
                myScore.UpdateOne(am)
                sw = False
            if line[0] == "G":
                sw = True

最好将 Score 实例传递给该函数,并让它在读取文件时对其进行更新。

def processScores(file, score):
    with open(file, 'r') as f:
        for line in f:
            if line[0] == 'G':
                amount = int(next(f)) # read next line & convert to integer
                score.UpdateOne(amount)

然而,如果让它成为一种提供更好的方法 encapsulation,或者在其中捆绑数据和函数,那就更好了——这是面向对象编程的一个重要原则。这样,如果您更改存储在 class 实例中的信息、更新的方式或数据文件的格式,您必须在一个地方进行更改。

    def processScores(self, file):
        with open(file, 'r') as f:
            for line in f:
                if line[0] == 'G':
                    amount = int(next(f)) # read next line & convert to integer
                    self.UpdateOne(amount)