python helper函数_python类中的classmethod和helper函数

简单的答案是:make_with_sums和make_with_products是类方法,而不是实例方法,因此需要这样声明它们。另外,请注意,_make_with_helper也需要将一个起始的值作为参数;将var初始化为0将使make_with_product返回{}。在

无论传递给method_dict的输入是相同的,因此它应该是一个类变量:class dnryNumbers(object):

def __init__(self, big_number):

self.number = big_number

method_dict = {'sum': lambda x, y: x + y,

'prod': lambda x, y: x * y

}

@classmethod

def _make_with_helper(cls, make_meth, fin_num, starting_value):

var = starting_value

for i in range(1, fin_num):

var = dnryNumbers.method_dict[make_meth](var, i)

return cls( var )

@classmethod

def make_with_sums(cls, sum_to):

return cls._make_with_helper('sum', sum_to, 0)

@classmethod

def make_with_product(cls, mul_to):

return cls._make_with_helper('prod', mul_to, 1)

但是现在,method_dict只是添加了一个你不需要的额外的间接层。由于函数不打算在类之外使用,所以只需将它们定义为“私有”方法,并直接使用对它们的引用。在

^{pr2}$

@类方法

def make_with_sums(cls,sum_to)定义为:

返回cls.\u make_with_helper(dnryNumbers.\u sum,sum_to,0)@classmethod

def make_with_product(cls, mul_to):

return cls._make_with_helper(dnryNumbers._prod, mul_to, 1)

最后,值得指出的是,除非您的实际代码比这里所示的示例更复杂,_sum已经可用作operator.add,_prod只是operator.mul,而{}只是reduce内置(或者{},如果python3)的重新实现。在import operator

try:

reduce

except NameError:

from functools import reduce

class dnryNumbers(object):

def __init__(self, big_number):

self.number = big_number

@classmethod

def _make_with_helper(cls, make_meth, fin_num, starting_value):

return cls(reduce(make_meth, range(1, fin_num), starting_value))

@classmethod

def make_with_sums(cls, sum_to):

return cls._make_with_helper(operator.add, sum_to, 0)

@classmethod

def make_with_product(cls, mul_to):

return cls._make_with_helper(operator.add, mul_to, 1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值