Class level variables in Python
mackstann
mack at incise.org
Wed Aug 27 19:59:32 EDT 2003
On Wed, Aug 27, 2003 at 04:43:03PM -0700, Brian Munroe wrote:
> I was wondering if someone could explain if there is any difference
> between initalizing your object attributes up in the __init__
> constructor or setting them up as (I am guessing at the name here)
> object level variables (like z)
Generally, if something is more or less constant, I make it a class
variable. If its value depends on the arguments passed to __init__, or
if it is something like a network connection, file operation, etc, then
it goes in __init__.
class Foo:
specialSequence = "blahblah"
def __init__(self, filename):
self.fp = file(filename, "r")
if self.fp.read(8) == self.specialSequence:
# .. do something ..
specialSequence has no reason to be in the constructor, but fp does. I
suppose that's a good guideline - if you can't think of a reason for it
to be in __init__, then don't put it there.
--
m a c k s t a n n mack @ incise.org http://incise.org
The four building blocks of the universe are fire, water, gravel and vinyl.
-- Dave Barry
More information about the Python-list
mailing list