Define Constants

Discussion in 'Python' started by codecraig, Apr 20, 2005.

  1. codecraig

    codecraig Guest

    I have a question about how to define constants.

    My directory structure looks like...

    --> utils

    Ok, CustomThing looks like...

    TOP = 0
    LEFT = 1

    class CustomThing:
    def __init__(self): = "foo"

    so, from 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??

    codecraig, Apr 20, 2005
    1. Advertisements

  2. 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()


    Steven Bethard, Apr 20, 2005
    1. Advertisements

  3. You're only importing the class. Try importing the whole module:

    from utils import CustomThing
    print CustomThing.TOP

    Eric Nieuwland, Apr 20, 2005
  4. codecraig

    codecraig Guest

    Thanks for the input.

    i am renaming my module to be customthing. I noticed that is how many
    python modules are, so I will stick to the "convention".

    Thanks for the help.
    codecraig, Apr 21, 2005
  5. codecraig

    beliavsky Guest

    beliavsky, Apr 21, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.