The notion of object depends on having instance variables (or
“attributes”) which have unique values for each object. We
can extend this concept to include variables that are not unique to each
instance, but shared by every instance of the class. Class level
variables are created in the class definition itself; instance variables
are created in the individual class method functions (usually
__init__).
Class level variables are usually "variables" with values that don't change; these are sometimes called manifest constants or named constants. In Python, there's no formal declaration for a named constant.
A class level variable that changes will be altered for all instances of the class. This use of class-level variables is often confusing to readers of your program. Class-level variables with state changes need a complete explanation.
This is an example of the more usual approach with class-level constants. These are variables whose values don't vary; instead, they exist to clarify and name certain values or codes.
Example 22.5. wheel.py
import random
class Wheel( object ):
"""Simulate a roulette wheel."""
green, red, black= 0, 1, 2
redSet= [1,3,5,7,9,12,14,16,18,19,21,23,25,27,30,32, 34,36]
def __init__( self ):
self.lastSpin= ( None, None )
def spin( self ):
"""spin() -> ( number, color )
Spin a roulette wheel, return the number and color."""
n= random.randrange(38)
if n in [ 0, 37 ]: n, color= 0, Wheel.green
elif n in Wheel.redSet: color= Wheel.red
else: color= Wheel.black
self.lastSpin= ( n, color )
return self.lastSpin
![]() | Part of definition of the class
|
![]() | The |
![]() | The |
![]() | The The |
The following program uses this Wheel class
definition. It uses the class-level variables red and
black to clarify the color code that is returned by
spin.
w= Wheel() n,c= w.spin() if c == Wheel.red: print n, "red" elif c == Wheel.black: print n, "black" else: print n
Our sample program creates an instance of
Wheel, called w. The program
calls the spin method of
Wheel, which updates
w.lastSpin and returns the tuple that contains the
number and color. We use multiple assignment to separate the two parts
of the tuple. We can then use the class-level variables to decode the
color. If the color is Wheel.red, we can print
"red".