Constants in python?

I have the following variables declared in many functions, since I need these values โ€‹โ€‹in each of them. In any case, can I declare them on a global scale or something like that, for example, I do not have to declare them in all my methods? I use all of these methods in the instance methods of my class.

x = 0
y = 1
t = 2

In C #, I simply declare them as global class variables, but the problem is that I donโ€™t always want to use them as self.x, self.y and self.z, since it gets my algorithm the code is uglier than it already is. How do you do this?

A typical use of this would be:

def _GetStateFromAction(self, state, action):
    x = 0
    y = 1
    t = 2

    if (action == 0):
        return (state[x], state[y] - 1, state[t])

    if (action == 1):
        return (state[x] - 1, state[y], state[t])
+3
source share
6 answers

, , . ( namesapaces)

MyModWithContstants.py

x = 0
y = 0

def someFunc():
  dosomethingwithconstants(x,y)

anotherMod.py

from MyModWithConstants import x
# and also we can do
import MyModWithConstants as MMWC

def somOtherFunc():
  dosomethingNew(x, MMWC.y)  
  ## x and MMWC.y both refer to things in the other file
+12

, , , :

class PathConstants(object):
    CSIDL_DESKTOP = 0
    CSIDL_PROGRAMS = 2

def get_desktop():
    return _get_path_buf(PathConstants.CSIDL_DESKTOP)

-y, setattr throw:

class ConstantExeption(Exception):
    pass

class ProgramConstants(object):
    foo = 10
    bar = 13
    def __setattr__(self, key, val):
        raise ConstantExeption("Cannot change value of %s" % key)

# got to use an instance...
constants = ProgramConstants()
print constants.foo
constants.bar = "spam"

:

10
Traceback (most recent call last):
  File "...", line 14, in <module>
    constants.bar = "spam"
  File "...", line 9, in __setattr__
    raise ConstantExeption("Cannot change value of %s" % key)
__main__.ConstantExeption: Cannot change value of bar
+5

(.. .py), self - . , , .

, , :

x, y, t = 0, 1, 2
+1

"" - , , . , .

+1

global x, y, z
x=0
y=1
z=2

?

0
import __builtin__
__builtin__.__dict__["X"] = 5

X , .

, , python . "_".

-1

Source: https://habr.com/ru/post/1724246/


All Articles