I’m having trouble creating an instance of a class using Python’s re module. Here’s what I’m trying to do:
- Loop over each line of many data files.
- If a line matches the format of a record, then create an instance of the Record class with the record’s two values as attributes.
I expect the following code fragment to print the string of five capital letters captured by the re module in the terminal() method for the Record class, but clearly I’m misunderstanding something. The actual output follows below the code.
class SrcFile:
def __init__(self, which):
self.name = which
class Record(SrcFile):
def terminal(self):
recordline = re.compile(r"^([A-Z]{5})\s{3}")
if recordline.match(self):
m = recordline.match(self)
return m.group(1)
for f in files:
file = SrcFile(f)
for l in f:
record = Record(f)
print(record.terminal())
Again, I expect to see a string of five capital letters for each record line, but what I actually get is:
Traceback (most recent call last):
File "./next.py", line 78, in <module>
print(record.terminal())
File "./next.py", line 63, in terminal
if recordline.match(self):
TypeError: expected string or buffer
It would also be helpful if someone could explain why, in the code
for f in files:
file = SrcFile(f)
for l in f:
record = Record(f)
it is apparently incorrect to use record = Record(file). I discovered this by trial and error, as I couldn’t access the methods of the SrcFile class for a file using record.method() with the incorrect code, but I don’t understand why.
I’m certain that my inexperience with programming in general and Python in particular is rather obvious. Thanks in advance for your help.
You mean to write
rather than
When you call
re.match, you’re supposed to do so with a string.selfis not a string, but rather aRecordobject, whileself.nameis the string set in the lineThere are two more basic problems that relate to your other question.
You’re never using the line itself,
l, which is the whole reason you’re iterating through the file. Perhaps you meant to writeRecord(l).Why does the Record class inherit the
SourceFileobject (with the codeclass Record(SourceFile)?) You should read more carefully about inheritance: inheritance is used to share methods and properties between multiple objects, and it doesn’t really apply to this code.