maacubast
maacubast

Reputation: 1

Python: How use constants for multiple clasess?

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")

Upvotes: 0

Views: 314

Answers (2)

Manoj Govindan
Manoj Govindan

Reputation: 74675

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]

Upvotes: 1

pyfunc
pyfunc

Reputation: 66709

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")

Upvotes: 0

Related Questions