【问题标题】:Override print function in child class from parent class从父类覆盖子类中的打印功能
【发布时间】:2018-08-01 21:11:25
【问题描述】:

我想知道是否有一种方法可以覆盖父类的子类中使用的python 3.x 中的内置打印函数?这可能吗?

【问题讨论】:

  • “覆盖子类中使用的python 3.x中的内置打印函数”是什么意思? print 不是一种方法。你的意思是__str__
  • 什么父类? Python 是一种函数式语言,所以是的,你可以覆盖任何你想要的函数。 print = lambda x:"This function returns this string"
  • 例如:class a(object): def __init__(self): builtins.print('inside init') self.abc = 1 def print(self): builtins.print('inside print ') def __str__(self): builtins.print('inside str') self.print() class b(a): def __init__(self): super(b,self).__init__() def a_on(self,log ): print('inside b') n = b() >>> inside b 我想覆盖 a 类中 b 类的打印,以便打印“内部打印”
  • 在 python 3.6.5 的 builtins.py 中: def print(self, *args, sep=' ', end='\n', file=None): # known special case of print " "" print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 将值打印到流,或者默认打印到 sys.stdout。可选的关键字参数: file: 类文件对象(流);默认为当前的 sys.stdout。sep: 插入值之间的字符串,默认一个空格。end: 附加在最后一个值之后的字符串,默认换行。flush:是否强制刷新流。"""通过
  • 有什么建议吗?

标签: python-3.x


【解决方案1】:
  1. 我无法找到 builtins.print 的真正定义,但这是我要覆盖的方法:
class ViewSpy:
    last_message = ""
    
    def print(self, *args, sep=' ', end='\n'):
        self.last_message = sep.join(map(str, args)) + end

根据布尔值更改v.print 的行为:

import builtins

# ... set should_unittest variable here 

if should_unittest:
    v = ViewSpy()
else:
    v = builtins
v.print("nothing")

ViewSpy 的实现模拟了builtins.print,并将输出存储到一个字段中,以便我们可以自动测试它。

def test_view_spies():
    v = ViewSpy()
    v.print("nothing")
    assert v.last_message == "nothing\n"

    v.print("something")
    assert v.last_message == "something\n"

    v.print("John", "Smith")
    assert v.last_message == "John Smith\n"

    v.print("apples", 24, "grapes", "bananas", sep=',')
    assert v.last_message == "apples,24,grapes,bananas\n"

    v.print("Automated testing is fun", end='!!!')
    assert v.last_message == "Automated testing is fun!!!"

    v.print("Maybe, you don't need a new line", end='')
    assert v.last_message == "Maybe, you don't need a new line"

  1. 给演示者
class Presenter:
    def __init__(self, view):
        self.view = view

    def present_sentence(self, response_model):
        self.view.print(*map(self.__convert_container_to_str, response_model))

    @staticmethod
    def __convert_container_to_str(each_character_as_array_element):
        return "".join(each_character_as_array_element)

现在我们可以读取p.present_sentence 将发送到控制台的内容并自动对其进行测试

def test_present_sentence():
    view = ViewSpy()
    p = Presenter(view)
    p.present_sentence(({'ь', 'е', 'с', 'Д', 'В', 'л', 'а'}, {'М', 'у', 'и', 'р', 'а', 'н'},
                        {'п', 'х', 'к', 'у', 'т', 'о', 'л', 'а', 'с'},
                        {'и', 'д', 'н', 'ч', 'у', 'з', 'ж', 'о', 'л', 'а', 'с'}, {'х', 'у', 'т', 'а', 'м'},
                        {'в', 'е', 'с'}, {'в', 'е', 'и', 'ж'}, {'в'}, {'х', 'т', 'i', 'а'}, {'в', 'о', 'з', 'н'},
                        {'и', 'л', 'ж', 'о'}, {'п', 'ь', 'и', 'р', 'н', 'к', 'у', 'о', 'л', 'с'},
                        {'ш', 'i', 'у', 'з', 'о', 'л', 'а', 'м'}, {'i', 'г', 'н', 'з', 'о', 'л', 'а', 'м'}))

    printed_words = view.last_message.split()
    first_word = view.last_message.split()[0]
    assert len(printed_words) == 14

    assert len(first_word) == 7
    for letter in first_word:
        assert letter in {'ь', 'е', 'с', 'Д', 'В', 'л', 'а'}

    assert view.last_message[-1] == '\n'
    assert view.last_message[13] != ' '
    assert view.last_message[14] == ' '
    assert view.last_message[15] != ' '

    third_word = printed_words[2]
    assert len(third_word) == 9
    for letter in third_word:
        assert letter in {'п', 'х', 'к', 'у', 'т', 'о', 'л', 'а', 'с'}

__init__.py中,我们编写以下代码来实际将消息打印到控制台,并且不存储日志。

import builtins

#...

p = Presenter(builtins)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2021-06-20
    • 2017-06-03
    • 2017-11-11
    相关资源
    最近更新 更多