单方法类改写成函数

2021-11-18  本文已影响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是否可以理解成类属性?

写在后面

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

上一篇 下一篇

猜你喜欢

热点阅读