Variables common to all objects of a class

Mark McEahern marklists at mceahern.com
Fri Apr 12 09:57:50 EDT 2002


[Thomas Guettler]
> How do you store variables which should be common to all
> objects of a class?

Short answer:

	class Foo:
		classVar = "whatever"

Example:

#!/usr/bin/env python

class Dog:

    species = "canine"

    def __init__(self, name=None):
        if not name:
            name = "mystery dog"
        self.name = name

    def bark(self):
        return "Hi, I'm a %s and my name is %s." % (Dog.species, self.name)

rover = Dog("rover")
fido = Dog("fido")

print rover.bark()
print fido.bark()

print Dog.species
print rover.species
print fido.species







More information about the Python-list mailing list