By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,519 Members | 1,792 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,519 IT Pros & Developers. It's quick & easy.

Define Constants

P: n/a
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.

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Jul 19 '05 #2

P: n/a
codecraig wrote:
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

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.