Как передать строку из функции в декоратор? - PullRequest
0 голосов
/ 23 апреля 2020

Я хочу получить входные данные от функции:

def input_text():
    text = input('Type the text:\n')
    # deco_required = input('Format variable\n')
    return text

Затем я хочу, чтобы декоратор отформатировал текст из введенного выше:

def center(input_text):
    def centering(*args,**kwargs):
        t = '<center>{}</center>' .format(kwargs)
        return input_text
    return centering

Я думал, что это было правильный путь к go об этом:

@centring
input_text()

Я получаю следующую ошибку:

File "<ipython-input-10-95c74b9f0757>", line 2
    input_text()
             ^ SyntaxError: invalid syntax

, которая не очень полезна для поиска.

1 Ответ

1 голос
/ 23 апреля 2020

Во-первых, без декоратора вы просто передали бы возвращаемое значение input_text центрирующей функции.

def centering(s):
    return '<center>{}</center>'.format(s)

centered_text = centering(input_text)

Функция, которая делает это за вас, может выглядеть как

def input_centered_text():
    text = input('Temp the text:')
    centered_text = centering(text)
    return centered_text

Декоратор, который может производить input_centered_text из оригинального input_text, будет выглядеть как

def center(f):
    def _():
        centered_text = f()
        return centered_text
    return _

и использоваться как

def input_text():
    text = input('Type the text:\n')
    return text


input_centered_text = center(input_text)

или

@center
def input_centered_text():  # Note the change in the function name
    text = input('Type the text:\n')
    return text
...