Constants in Python

  • Thread starter Brent W. Hughes
  • Start date
B

Brent W. Hughes

Warning: Newbie at work!

I was planning to write some code something like this:

class CTree:
LEAFSIZE = 4
LeafNode = [None] * LEAFSIZE
KEY,DATA,LEFT,RIGHT = range(LEAFSIZE)
#---------------------------------------------------
def Add(self,Node,SubTree):
Key1 = Node[KEY]
....

But then I realized that the last line (and many more similar lines)
would probably need to be writen thusly:

Key1 = Node[CTree.KEY]

I find this a little ugly, not to mention more typing. I suppose
I could move these lines:

LEAFSIZE = 4
KEY,DATA,LEFT,RIGHT = range(LEAFSIZE)

out of the class and make them global, but this kind of runs
against the grain.

Is there another way to deal with "constants"?
 
A

Andrew Koenig

I was planning to write some code something like this:
class CTree:
LEAFSIZE = 4
LeafNode = [None] * LEAFSIZE
KEY,DATA,LEFT,RIGHT = range(LEAFSIZE)
#---------------------------------------------------
def Add(self,Node,SubTree):
Key1 = Node[KEY]
But then I realized that the last line (and many more similar lines)
would probably need to be writen thusly:
Key1 = Node[CTree.KEY]

How about this?

Key1 = Node[self.KEY]

Seems consistent with other class-relative usages.
 
J

John Lenton

Warning: Newbie at work!

I was planning to write some code something like this:

class CTree:
LEAFSIZE = 4
LeafNode = [None] * LEAFSIZE
KEY,DATA,LEFT,RIGHT = range(LEAFSIZE)
#---------------------------------------------------
def Add(self,Node,SubTree):
Key1 = Node[KEY]
...

But then I realized that the last line (and many more similar lines)
would probably need to be writen thusly:

Key1 = Node[CTree.KEY]

I find this a little ugly, not to mention more typing. I suppose
I could move these lines:

LEAFSIZE = 4
KEY,DATA,LEFT,RIGHT = range(LEAFSIZE)

out of the class and make them global, but this kind of runs
against the grain.

Is there another way to deal with "constants"?

not as far as I know. I'm just posting to underline what Andrew just
said: you want to do self.KEY, not CTree.KEY; the latter is a disaster
from a code reusability standpoint, because you just rendered your
class unsubclassable. Well, not quite, but you certainly restricted it
a lot.

--
John Lenton ([email protected]) -- Random fortune:
Deliver yesterday, code today, think tomorrow.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBPbPIgPqu395ykGsRAsCiAKCRJzA0qPvfPW/OBXvP4BwWp7Z+TQCgwoDa
Kw2lBVDedqSN2OpIK+p4jXU=
=w4DA
-----END PGP SIGNATURE-----
 

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
474,206
Messages
2,571,069
Members
47,674
Latest member
scazeho

Latest Threads

Top