Найти - Пользователи
Полная версия: Переменные
Начало » Python для новичков » Переменные
1
gnom
Как можно сделать что бы в одном фаиле лежали значения констант например а в другом сам механизм.
Zubchick
создать файл с константами, а из файла с логикой импортировать его :)
gnom
а каким образом то =0
Soteric
data.py
ALPHA = 'Альфа'
BRAVO = 'Браво'
CHARLIE = 'Чарли'
logic.py
from data import ALPHA
from data import BRAVO
from data import CHARLIE

print(ALPHA)
print(BRAVO)
print(CHARLIE)
gnom
ц жалко я думал что указав один файл можно ипортировать все переменные не перечесляя их(
Soteric
Можно так:

data.py
class Data(object):
ALPHA = 'Альфа'
BRAVO = 'Браво'
CHARLIE = 'Чарли'
logic.py
from data import Data

print(Data.ALPHA)
print(Data.BRAVO)
print(Data.CHARLIE)
Или так:

data.py
ALPHA = 'Альфа'
BRAVO = 'Браво'
CHARLIE = 'Чарли'
logic.py
from data import *

print(ALPHA)
print(BRAVO)
print(CHARLIE)
gnom
о то что надо спасибо
Soteric
Исправил сообщение. См. снова :)
Vadim
Записать код в файл, потом прочитать этот файл и исполнить его командой _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’)
функция создает байт-компилированную версию.

учтите что при такой раскладке в файле последняя строка должна обязательно кончаться на \n иначе ошибка
Locals и Globals - словари, соответственно, локального и глобального пространств имен, если locals не указано то оно по дефолту считается равным globals
Vadim
Вот пример программы
файл называется 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)
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB