Assign a print statement to a variable in a function in Python 2.7

前端 未结 3 978
生来不讨喜
生来不讨喜 2021-01-29 12:38

I\'m trying to assign a print statement to a variable in a function:

def namer(fn, ln=\'Smith\'):
    # return value, default value
    r = print \"Your name is          


        
3条回答
  •  忘掉有多难
    2021-01-29 13:18

    Although it doesn't make sense to assign a print statement it makes sense to assign a print function to variable.

    In this case you need to use the following import (only if using python 2)

    from __future__ import print_function
    

    A possible use case

    import logging
    
    use_print = True
    if use_print:
        log_fun = print
    else:
        log_fun = logging.info
    
    log_fun('Spam')
    

    The following statement will also be syntactically correct but it won't make sense

    r = print('Something')
    

    You will end up printing "Something" and assign None to r which is the return value of print function

提交回复
热议问题