Explicit recommendation: DO NOT USE the following.
and please ease-up on the downvotes...
Edit: I even found a quote from Alex Martelli expressing how bad an idea my snippet is.
(Short excerpt from Python in a Nutshell, 2nd ed. O'Reilly 2006)
Use exec only when it is really indispensable. MOst often, it's best to avoid exec choose more specific, well-well controlled mechanisms instead: exec pries loose your control on your code's namespace, damages performance and exposes you to numerours, hard-to-find bugs.
Therefore here is my not so pythonic moment:
class Log:
BAT_STATS = ['AB', 'R', 'H', 'HR']
def __init__(self):
for cat in Log.BAT_STATS:
exec('self.' + cat + ' = 0')
Using setattr() is of course cleaner (I recommend it in this simple case), but it's nice to remember the power of exec... A bit like being reminded of a dangerous tool we have in the shed.