views:

60

answers:

2

Hi! I want use a constant in Python for 2 classes. Which is the better way? Thanks in advance!

MY_COLOR = "#000001" # <-------- Are correct here?
BLACK = "#000000"    # <-------- Are correct here?

class One:

    MY_FONT = "monospace"

    def __init__(self):
        if MY_COLOR == BLACK:
            print("It's black")

        if self.MY_FONT == "monospace":
            print("Font equal")


class Two:

    def __init__(self):
        if MY_COLOR == BLACK:
            print("It's black")
+1  A: 

The location of the "constant" looks fine to me. As @pyfunc commented you might want to declare other color/font values as "constant"s as well.

If you are expecting a lot of custom colors and/or fonts you might want to think of a separate module or a properties/configuration file.

[pedantic] There is no "constant" in Python the way you seem to imply. You are setting a variable at the module level, that is all. The all caps is a convention used to indicate that the value shouldn't be changed. There is nothing preventing it from being changed. [/pedantic]

Manoj Govindan
@Manoj: +1 , I should have added that on the notes
pyfunc
+1 because you pedantic comment
joaquin
Thanks Manoj! I asked because I thought the "constant" position could be better (In OOP), but I could not find a better way.
maacubast
Wait a minute. Two people voted for me and I see only one up vote. I call shenanigans =P =P
Manoj Govindan
A: 

Something like this should be better:

BLACK = "#000000"
GREY  = "#111111"
MONO  = "monospace"

class One:
    def __init__(self, color, font ):
        if color == GREY:
            print("Color not equal")

        if font == "MONO:
            print("Font equal")
pyfunc
Well, my question is not about the hardcode (It's only an example) :P I asked about the better POSITION for a "constants" for 2 or more classes :) Thanks pyfunc!
maacubast