Dynamically adding a runtime generated method to a class.
"Martin v. Löwis"
martin at v.loewis.de
Fri Nov 30 02:26:52 EST 2007
> This would work and not be too terribly inefficient but I was thinking
> it would be much better generate the getLine method at runtime and
> dynamically add it to the class so I wouldn't have to pass the columns
> around and loop through them every time;
I would advise against that. Generating methods on the fly is fairly
involved (although possible); but I see no gain.
If you don't want to pass the cols around (which I can see as
desirable), I recommend to make them an instance variable:
def getLine(self, per):
vals = [self.desc]
for col in self.cols:
vals.append(col(self, per))
return vals
line1 = lineClass1('Some Description', [1,2,3,4,5,6,7,8,9,10,11,12])
line1.cols = [lineClass1.Ptd, lineClass1.Ytd]
print line1.getLine(5)
HTH,
Martin
More information about the Python-list
mailing list