美文网首页
单方法类改写成函数

单方法类改写成函数

作者: 码男将将 | 来源:发表于2021-11-18 07:20 被阅读0次

    前言:

    来自python cook的知识点,看完就觉得发现了新大陆.但是目前还没想好这么做能有啥好处 hah.现在分享出来大哥们看完如果有好的使用场景跪求帮上课.

    问题:

    有一个方法每次被调用都要记录调用的次数,并且会返回目前被调用了多少次

    类实现

    class TestClass:
      def __init__(self):
        self.count = 0
      def print_word(self, word)
        self.count += 1
        print("调用次数:{}--单词:{}".format(self.count, word)
    
    if __name__ == "__main__":
      temp = TestClass()
      temp.print_word("hello") #调用次数:1--单词:hello
      temp.print_word("world") #调用次数:2--单词:world
    

    改为函数实现

    def shell():
      count = 0
      def print_word(word):
        nonlocal count
        count += 1
        print("调用次数:{}--单词:{}".format(count, word)
      return print_word
    if __name__ == "__main__":
      temp = shell()
      temp("hello") #调用次数:1--单词:hello
      temp("world") #调用次数:2--单词:world
    

    结论

    类是使用了实例属性去做的次数累加,对象不销毁count变量可以一直用作计数
    函数使用了闭包特性,内部函数使用了外部函数的变量count进行计数.脑袋稍微绕一下,这个外部函数的变量count是否可以理解成类属性?

    写在后面

    原文作者说:"任何时候只要你碰到需要给某个函数增加额外的状态信息的问题,都可以考虑使
    用闭包。相比将你的函数转换成一个类而言,闭包通常是一种更加简洁和优雅的方案"
    可以说是优雅永不过时!!!

    相关文章

      网友评论

          本文标题:单方法类改写成函数

          本文链接:https://www.haomeiwen.com/subject/tfgdtrtx.html