[Tutor] What is a "state variable"?

Steven D'Aprano steve at pearwood.info
Fri Nov 12 03:09:11 CET 2010


Emile van Sebille wrote:

> "A class is a container for shared state, combined with functions 
> (methods) that operate on that state. By putting state variables into 
> member fields, they are accessible to all the methods of the class 
> without having to be passed as parameters."
> 
> So, by his own definition state variables are parameters.

An example might help clarify this. Suppose you have a class with a 
method that takes various parameters:

class Parrot:
     def talk(self, text, loud, squawk):
         if squawk:
             text += " Squawk!!!"
         if loud:
             text = text.upper()
         print(text)


Parrot instances don't have any state (which kinda defeats the purpose 
of using an object, but never mind) but you have to provide extra 
arguments to the method:

polly = Parrot()
polly.talk("Polly wants a cracker!", False, True)


We can give the instance state and reduce the arguments given to the method:

class Parrot:
     def __init__(self, squawks=True, loud=False):
         self.squawks = squawks
         self.loud = loud
     def talk(self, text):
         if self.squawks:
             text += " Squawk!!!"
         if self.loud:
             text = text.upper()
         print(text)


polly = Parrot()
polly.talk("Polly wants a cracker!")


In Python, nearly all objects have state. Even ints and floats have 
state -- their state is their value. Exceptions are:

None
NotImplemented
direct instances of object (not subclasses of object)

and possibly one or two others that I haven't thought of.



-- 
Steven



More information about the Tutor mailing list