Python: Special Class Methods
I have really been trying to learn some Python fundamentals lately, reading some books and taking an online class. So: wow. I can’t believe that I have written so many tools, some used by really competent people at large companies, without really understanding polymorphism and other basic Python concepts.
Here’s an example of my sequence method from before, but making it a class using special class methods:
http://docs.python.org/reference/datamodel.html#specialnames
class imSequence: def __init__(self, file): dir = os.path.dirname(file) file = os.path.basename(file) segNum = re.findall(r'\d+', file)[-1] self.numPad = len(segNum) self.baseName = file.split(segNum)[0] self.fileType = file.split('.')[-1] globString = self.baseName for i in range(0,self.numPad): globString += '?' self.images = glob.glob(dir+'\\'+globString+file.split(segNum)[1]) def __len__(self): return len(self.images) def __iter__(self): return iter(self.images) |
Here’s an example of use:
seq = imSequence('seq\\test_00087.tga') print len(seq) >>94 print 'BaseName: %s FileType: %s Padding: %s' % (seq.baseName, seq.fileType, seq.numPad) >>BaseName: test_ FileType: tga Padding: 5 for image in seq: print image >>seq\test_00000.tga >>seq\test_00001.tga >>seq\test_000002.tga ... |
[More info and examples: Dive Into Python: Special Class Methods]
Clever! Thanks for sharing it!
Comment by maximd — 2010/08/27 @ 10:33 PM
Love your Python blogs. Which online class did you attend, and would you recommend it?
Comment by Jon — 2010/08/29 @ 4:27 PM