Variables common to all objects of a class

Terry Reedy tejarex at yahoo.com
Fri Apr 12 09:49:28 EDT 2002


"Thomas Guettler" <zopestoller at thomas-guettler.de> wrote in message
news:3CB6CD99.70409 at thomas-guettler.de...
> Hi!
>
> How do you store variables which should be common to all
> objects of a class?

You should call instances of a class instances since 'object' is a
generic term that in Python includes everything..  Class variables are
usually defined within the class statement.  They can also be assigned
after creation of the class, as in

class.attribute = value

> I would do it like this. Is this the right pyhton-way?

To my knowledge, no.

> #foo.py
> class_variable=0

This is a module (aka global) variable.

> def class_method():
>      print "I work only on class variables"

Putting class methods outside the class is a kludge was previously
necessary since methods within the class are taken to be instance
methods.  The 2.2 release seeks to remedy this with the new mechanism
for static and class methods.

> class foo:
>      object_variable=1

This is a class variable (altough some people define instance
variables as class variables to document or give default values).  It
can be accessed directly as foo.object_variable or indirectly as
instance.object_variable if there is no instance variable of the same
name.

>      def my_class_variable(self):
>          print "cv", class_variable, "ov", self.object_variable
>
> if __name__=="__main__":
>      f=foo()
>      f.my_class_variable()
>      import foo
>      foo.class_method()

Importing a module into itself strikes me as problematic.

Terry J. Reedy






More information about the Python-list mailing list