I’m tempted to define my Python classes like this:
class MyClass(object):
"""my docstring"""
msg = None
a_variable = None
some_dict = {}
def __init__(self, msg):
self.msg = msg
Is declaring the object variables (msg, a_variable, etc) at the top, like Java good or bad or indifferent? I know it’s unnecessary, but still tempting to do.
When you declare a class, Python will parse its code and put everything in the namespace of the class; then the class will be used as a kind of template for all objects derived from it – but any object will have its own copy of the reference.
Note that you always have a reference; as such, if you are able to alter the referenced object, the change will reflect into all places it is being used. However, the slot for the member data is unique for each instance, and therefore assigning it to a new object will not reflect to any other place it is being used.
Note: Michael Foord has a very nice blog entry on how class instantiation works; if you are interested in this topic, I suggest you that short reading.
Anyway, for all practical uses, there are two main differences between your two approaches:
Usually, reviewing code I see members declared at class level with a bit of suspicion; there are a lot of good usecases for them, but it is also quite likely they are there as a kind of habit from previous experiences with other programming languages.