Matt Matt - 4 months ago 17
Python Question

Why is this invalid syntax? (Class function)

The code I am trying to enter (python) looks like this:

class RainfallTable:
def _init_ (self, njrainfall.txt):
self.njrainfall.txt = open(njrainfall.txt, 'r')
def close(self):
if self.t:
self.t.close()
self.t = None


I am trying to get this class to simply open a file called njrainfall.txt, but I get the following error message when I do so:

File "3Homework.py", line 2
def _init_ (self, njrainfall.txt):
^


What am I doing wrong?

Answer

You've got a . in your variable names, which is invalid syntax for python. Remove those in your njrainfall.txt variables. A good substitute would be njrainfall_file or something similar. Secondly, the init functions is written with two underscores, like so:

def __init__(self, njrainfall_file):

Here some code:

class RainfallTable:
    def __init__(self, njrainfall_file):
        self.njrainfall_file = open(njrainfall_file, 'r')
    def close(self):
        if self.t:
            self.t.close()
            self.t = None

Make sure to pass njrainfall_file as a string of filename!

Comments