-1

What I am trying to do here is read a line of a file. If the content in the file meets the correct criteria execute one of the definitions in my class. The thing is I have no clue on what kind of code I need for this.

here is what I have so far:

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

The Idea is that processScores will be ran. As the code reads the file line by line if it finds a certian marker in the line example G then the next line it reads shall be input into the def updateOne. But thats just an example.

Anyideas on what I can do better?

Thank you

Christopher Jakob
  • 91
  • 1
  • 2
  • 11
  • You can define a switch that changes to True when line is G. When first in the loop, evaluate the switch and if it's True read the line and call the method with the parameter. – Trimax Jan 16 '15 at 07:31

2 Answers2

1

It would be better to pass a Score instance to the function and have it update it as it reads the file.

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)

However it would be even better than that to make it a method to provide better encapsulation, or bundling of data and functions within it — which is an important principle of object-oriented programming. This way if you change what information is stored in instances of class, how it updating is done, or how the data file formatted, you have to make changes in one place.

    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)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • thank you. Your solution is fantastic. she what I couldn't figure out was how to connect the class and the read file process. Never would I have thought to ad Score to the processScores input. It makes a ton of sense. then you set a variable amount which takes the place of the amount input in updateOne. Perfect. thank you. I have learned a great deal from this – Christopher Jakob Jan 17 '15 at 00:50
-1

You want something like this:

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
Trimax
  • 2,413
  • 7
  • 35
  • 59
  • You can't use assignment in conditional expressions, comparing a boolean variable with either True or False is tautological ("if a == True" is the same as "if a"), don't use 'file' as variable name, as it's a builtin, and last but not least, you file-variable isn't used in the open, instead you pass a string containing "file". – deets Jan 16 '15 at 10:25
  • @deets: I agree with most of your points, except for the restriction on the use of "file" as a variable name. Yes, it's a built-in, but when was the last time you needed to use it? The recommended way to create files is by calling the built-in `open()` function, _not_ the `file()` class constructor. – martineau Jan 17 '15 at 11:56
  • @mantineau I think it's a good rule of thumb to not re-define any builtins. Then less accidents happen, and no pylint warnings. And yes, I always use open - but I'd use isinstance(var, file). Last but not least - I'd use a better name anyway, e.g. filename. But yes, file as such is rarely used. – deets Jan 17 '15 at 18:59
  • @deets: pylint warnings about it could easily be suppressed if not just ignored. Regardless, I also don't think your example of using `isinstance(var, file)` is very credible or convincing. First of, in general such type checking is discouraged in Python, and secondly, that wouldn't be a very good way to detect a "file-like" object -- when was the last time you derived a subclass with `file` as a baseclass (or saw it being done)? – martineau Jan 18 '15 at 18:06
  • @deets: One anomaly I found was in [this answer](http://stackoverflow.com/a/1661454/355230) where a legitimate case is made that using `isinstance(var, file)` could be useful -- but it's a pretty exceptional situation (and the author admits "isn't very Pythonic"). – martineau Jan 20 '15 at 16:08
  • @martineau I agree that it's rare. IMHO when teaching python to somebody who's obviously still struggling with being comfortable with the language, I think a rule of thumb that say "never" is easier to give and follow instead of the obviously more correct "don't do it unless you know what you are doing". Which you do, and I do, but I doubt the OP of this answer does. Context matters. – deets Jan 21 '15 at 09:09
  • You treat your rule of thumb more like an hard and fast rule rather than an approximate principle. Heaven forbid we mention anything to the noobs that required any thought like by saying "usually, but not always". Sorry, but it reminds me of the quote that starts "A foolish consistency is the hobgoblin of little minds..." – martineau Jan 21 '15 at 09:54