Форум сайта python.su
Как можно сделать что бы в одном фаиле лежали значения констант например а в другом сам механизм.
Офлайн
создать файл с константами, а из файла с логикой импортировать его :)
Офлайн
а каким образом то =0
Офлайн
data.py
ALPHA = 'Альфа'
BRAVO = 'Браво'
CHARLIE = 'Чарли'
from data import ALPHA
from data import BRAVO
from data import CHARLIE
print(ALPHA)
print(BRAVO)
print(CHARLIE)
Офлайн
ц жалко я думал что указав один файл можно ипортировать все переменные не перечесляя их(
Офлайн
Можно так:
data.py
class Data(object):
ALPHA = 'Альфа'
BRAVO = 'Браво'
CHARLIE = 'Чарли'
from data import Data
print(Data.ALPHA)
print(Data.BRAVO)
print(Data.CHARLIE)
ALPHA = 'Альфа'
BRAVO = 'Браво'
CHARLIE = 'Чарли'
from data import *
print(ALPHA)
print(BRAVO)
print(CHARLIE)
Отредактировано (Ноя. 14, 2010 17:02:22)
Офлайн
о то что надо спасибо
Офлайн
Исправил сообщение. См. снова :)
Офлайн
Записать код в файл, потом прочитать этот файл и исполнить его командой _exec_()
вот документация по интересуещей вас функции, взято с http://docs.python.org/library/functions.html
execfile(filename[, globals])
This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module.
The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object.
Changed in version 2.4: formerly locals was required to be a dictionary.
If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None.
Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function’s locals.
execfile('filename')
if os.path.isfile(’/home/Myfile.py’):
execfile(’/home/Myfile.py’)
Отредактировано (Ноя. 18, 2010 17:48:01)
Офлайн
Вот пример программы
файл называется Myfile.py
global max
a = 0
b = 1
count = 0
while count < max:
a, b=b, a+b
count += 1
print b
globals = {'max':100}
execfile('/home/vadim/Myfile.py', globals)
Офлайн