if I declare a const class which are contains variables:
for example
class const:
MASTER_CLIENT_CONNECTED = 0
CLIENT_CONNECTED = 1
GET_SERVER_QUEUE = 9998
ERROR = 9999
is there any way to reach this variable(constants) without creating a new class.
like this:
import const
const.MASTER_CLIENT_CONNECTED
or
import const
if(i==MASTER_CLIENT_CONNECTED):
You cannot declare a variable or value as constant in Python.
In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero. A program that demonstrates the declaration of constant variables in C using const keyword is given as follows.
Yes, instead of putting them in a class put them directly into your module (name the file e.g. const.py
so the module name is const
). Using a class for this is pretty much abusing classes for namespacing - and Python has packages/modules for this purpose.
Then you could even use from const import *
to import all globals from this module if you don't want to write const.
in front of everything. However note that this is usually discouraged as it potentially imports lots of things into the global namespace - if you just need one or two constants from const import ABC, DEF
etc. would be fine though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With