I’m passing a set of MovieFile objects from x.py to y.py and iterating through them, trying to use each object’s attributes in y.py
x.py
mfSet = {}
def pop():
## populate mfSet with MovieFile objects
m = MovieFile(title=t, year=y, dir=d, filename=f)
mfSet.setdefault(str(m), []).append(m)
class MovieFile():
def __init__(self, title, dir, filename, year=0):
self.title = title
self.year = year
self.fulltitle = title if year == 0 else title + ' (' + year + ')'
self.dir = dir
self.filename = filename
def __str__(self):
return repr(self.title + ' (' + self.year + ') at ' + self.dir)
y.py
from x import MovieFile, mfSet, pop # not sure if I need to import MovieFile
pop()
for mf in mfSet:
ft = mf.fulltitle # stacktrace says this attr doesn't exist for str object
title = mf.title # printing shows that this is "<built-in method title of str object at 0x10d84a3f0>"
So my main questions are:
Why are the MovieFile objects compiling as str objects, and how can I use the fulltitle attr once I get use of those objects?
You haven’t shown what
popis (please include that code, it’s the important bit). However, I expect what the problem is thatmfSetis adictand you are assigningstrkeys—perhapsmfSet[str(mf)] = mf. Iteration of adictproduces the keys, not the values of a dictionary.You may want to use a
setinstead of adict. Or, changefor mf in mfSet:tofor mf in mfSet.itervalues():(and change the variable namemfSetto not be misleading about type; PEP 8 also recommends against camelCase in variable names).So, you’re grouping by
MovieFile.__str__(). Very well, then. Here’s how I might write that code:And y.py:
Because you’re working with lists being the values, you’ve got another level of iteration to do.