2

このコードから得られるのは、Python の print はwritemethod ofのラッパー関数であるstdoutため、戻り値の型を指定すると、それも返さなければならないということだけです。では、なぜそれができないのでしょうか。

import sys
class CustomPrint():
    def __init__(self):
        self.old_stdout=sys.stdout

    def write(self, text):
        text = text.rstrip()
        if len(text) == 0: return
        self.old_stdout.write('custom Print--->' + text + '\n')
        return text
sys.stdout=CustomPrint()
print "ab" //works
a=print "ab" //error! but why?
4

1 に答える 1

4

python2.x ではprintステートメントです。だから、a = print "ab"違法な構文です。ただ試してみてくださいprint "ab"

Python3 では、print関数です。つまり、次のように記述します a = print("ab")。python2.6 以降では、 経由で python3 のprint関数にアクセスできることに注意してくださいfrom __future__ import print_function

最終的に、あなたが望むのは次のようなものです:

#Need this to use `print` as a function name.
from __future__ import print_function
import sys   

class CustomPrint(object):
    def __init__(self):
        self._stdout = sys.stdout
    def write(self,text):
        text = text.rstrip()
        if text:
            self._stdout.write('custom Print--->{0}\n'.format(text))
            return text
    __call__ = write

print = CustomPrint()

a = print("ab")
于 2013-03-09T16:17:50.747 に答える