Define Constants

C

codecraig

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??

Thanks.
 
S

Steven Bethard

codecraig said:
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
 
E

Eric Nieuwland

codecraig said:
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??

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

from utils import CustomThing
print CustomThing.TOP

--eric
 
C

codecraig

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top