python如何简便的给某段代码中的print加参数?

def func():
    ...
    print('test')
    ...

func 里面好多 print...

想使用类似装饰器的方式改成:

def func():
    ...
    print('test', file=stream)
    ...

如何操作?

阅读 2.6k
3 个回答

https://stackoverflow.com/que... Redirect stdout to a file in Python? - Stack Overflow

os.dup2标准输出重定向吧, 调用func前(或者直接对func使用装饰器)重定向了,完事儿后再修改回来。

感觉您说的应该是装饰器@property吧,直接把类方法当成类属性来使用

贴一段代码,参考廖学峰的官方网站

class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value


>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
  ...
ValueError: score must between 0 ~ 100!

你想表达的是什么意思?file和stream又从哪里来??字符串参数化?
比如

def say(name):
    print '{} dont know what the fuck are you talking'.format(name)
say('chosenone')
say('noone')


>>> chosenone dont know what the fuck are you talking
>>> noone dont know what the fuck are you talking
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题