0

Я пытаюсь модернизировать ф-ю print, что бы в случае условия все ф-и print в скрипте писали в файл.

Код:

def print_to_file(*txt, output_file):
    with open (file, 'w') as f:
        original_print(*txt, file = output_file)

if cond:
    original_print = print
    global print
    print = print_to_file

1 ответ 1

0

Инструкция global должна писаться до обращения к переменной. Это повышает удобность чтения кода, и никак не влияет на исполнение. В данном случае можно написать вот так и ничего не поменяется:

def print_to_file(*txt, output_file):
    with open (file, 'w') as f:
        original_print(*txt, file = output_file)

if cond:
    global print
    original_print = print
    print = print_to_file
1
  • Вне функций global не нужно, глобальный print перезапишется и так.
    – insolor
    14 ноя 2019 в 14:11

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.