2014-05-16 56 views
0

我定义了一个类Device,其中有很多子类,例如Microcontroller类的继承和定制

设备有两种模式,尤其是“模拟”模式。

我试图代码Device类等具有如果Microcontroller是那么当进行打印,应该由[simulated]前缀字符串模拟模式:

print "Hey !!" 
> [simulated] Hey!! 

我不知道如何下手,如果有可能超载print

+0

您将需要创建自己的打印函数来检查微控制器是否在模拟器中,如果是,则添加必要的前缀。 – Ryan

+0

好吧,但有可能超载打印? (像运营商) – Katsu

+0

@Katsu你不能超载打印作为一个声明,你必须自己做一个功能。 –

回答

0

您可以实现一些记录器类,并将其用于记录。你可以做圆顶对象注入来代替记录器的类型。例如:

class Logger: 
    def __init__(self, prefix): 
     self.prefix = prefix 
    def log(self, msg): 
     print('[{}] {}'.format(self.prefix, msg)) 


class Base: 
    def set_logger(self, logger): 
     self.logger = logger 


class Test(Base): 
    def do_something(self): 
     self.logger.log('Hey !!') 


test = Test() 

test.set_logger(Logger('simulated')) 
test.do_something() 

test.set_logger(Logger('very real')) 
test.do_something() 

例如:

[simulated] Hey !! 
[very real] Hey !! 
+0

谢谢!你回答了我的问题 – Katsu

0

我会建议你千万不要用在真正的代码,这种方法前言这个答案。然而,为了完整性(并且它回答了原始问题),我想我会在这里添加它。

因此,您可以通过重定向sys.stdout即时重定向并捕获print报表。

您可以从定义类似文件的对象开始,该对象捕获stdout并重定向到... stdout。在地方

import sys 

class OutputFormatter(object): 
    def __init__(self,prefix="",suffix=""): 
     self.prefix = prefix 
     self.suffix = suffix 

    def write(self,msg): 

     # As you want to change the behaviour of the print statement, 
     # you need to ignore solitary newlines that are sent to stdout 

     if msg != '\n': 

      # reformat the message passed by print 
      msg = " ".join([self.prefix,msg,self.suffix]) 

     # redirect back to stdout 
     sys.__stdout__.write(msg) 

有了这个,你可以用它来代替sys.stdout产生你所描述的“覆盖”类型的打印行为。

class Device(object): 
    def set_simulated(self): 
     # in simulated mode, use the stdout redirect 
     sys.stdout = OutputFormatter(prefix="[simulated]",suffix="") 

    def set_real(self): 
     # in real mode make sure to return to proper stdout 
     sys.stdout = sys.__stdout__ 


class Microcontroller(Device): 
    def __init__(self): 
     super(Microcontroller,self).__init__() 
     self.set_simulated()  
     print "This is simulated" 

     self.set_real() 
     print "This is real" 

Microcontroller() 

这将以下内容打印到终端:但是

[simulated] This is simulated 
This is real 

当心,这是给stdout行为的全球变化将影响所有的打印语句如果Device子类已设置为模拟模式。

对于需要上下文相关消息的系统,更好的方法是使用logging module或采用BSH建议的方法。