Define Constants

Steven Bethard steven.bethard at gmail.com
Wed Apr 20 17:15:01 EDT 2005


codecraig wrote:
> Hi,
>   I have a question about how to define constants.
> 
>   My directory structure looks like...
> 
> C:\
>     --> abc.py
>     --> utils
>         --> __init__.py
>         --> CustomThing.py
> 
>   Ok, CustomThing looks like...
> 
> TOP = 0
> LEFT = 1
> 
> class CustomThing:
>     def __init__(self):
>         self.foo = "foo"
> 
> 
> 
>   so, from abc.py I have
> 
> from utils.CustomThing import CustomThing
> 
> print CustomThing.TOP
> 
> but i get an error: AttributeError: class 'CustomThing' has no
> attribute 'TOP'
> 
> How can I access those??

Note that TOP and LEFT are delcared in the *module* CustomThing, not the 
*class* CustomThing which is what you get if you do

     from utils.CustomThing import CustomThing # the *class*

You should probably write your code as something like:

     import utils.CustomThing
     print utils.CustomThing.TOP

and if you need to use the class, write:

     t = utils.CustomThing.CustomThing() # create a new CustomThing

Also, if you've just started this, it might be worth checking out 
PEP8[1] which suggests that modules "should have short, lowercase names, 
without underscores".  If you're stuck with such a long module name, you 
might try:

     import utils.CustomThing as thing
     print thing.TOP
     t = thing.CustomThing()

STeVe

[1]http://www.python.org/peps/pep-0008.html



More information about the Python-list mailing list