Python常见面试题015.请实现一个如下功能的函数

发布时间 2023-04-03 16:35:06作者: 松勤吴老师

015. 请实现一个如下功能的函数

来自python黑魔法

题目

  • 实现一个add函数,可以"反复"调用,得到累加的结果
def add(num):
    ...
add(1)  # 输出1
add(2)  # 输出2
add(1)(2) # 输出3(即1+2)
add(1)(2)(3) # 输出6

思考

  • 一开始我想到的是用一个参数,类型是list,能保存用户的传参,请参考之前写的,python常见面试题003

    def add(num,container=[]):
        container.append(num)
        return sum(container)
    
    print(add(1)) # 1
    print(add(2)) # 3
    print(add(3)) # 6
    
  • 显然与题意不符,只是有点那味而已



  • 回想下装饰器的万能公式,好像有点对味

    def decorate(function_name):
        def inner():
            function_name()
        return inner
    
    @decorate
    def target(): # 一旦被装饰,target = decorate(target)
        print('calling target')
    
    target() # 此处的target变了
    
  • 但如何实现还是个问题

答案

  • 有装饰器的样子,只不过内部是个class

  • 但怎么去存储之前的值呢?

  • 答案看的我有点懵

    def add(num):
        class Myadd(int):
            def __call__(self, num):
                # print(self.numerator) # 你可以看到这个numerator就是最后一次调用前的和
                return Myadd(self.numerator+num)
        return Myadd(num)
    
    
    print(add(1)(2)(3))
    
  • Myadd继承int,主要是为了拿到int的一个property==>numerator

  • 这个numerator我查了一圈不太知道他是个啥,为何能存储用过的数据

  • 定义

        numerator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
        """the numerator of a rational number in lowest terms"""
    
  • 翻译:the numerator of a rational number in lowest terms

    • 最小有理数的分子
  • int还有一些其他的属性(仅作了解)

    • denominator:最小有理数的分母

          denominator = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
          """the denominator of a rational number in lowest terms"""
      
    • imag:复数虚部

      imag = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
      """the imaginary part of a complex number"""
      
    • real:复数实部

      real = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
          """the real part of a c0omplex number"""
      
  • 所以为何这个最小有理数的分子能存储呢?要去so上问问了。有了答案我再更新~