简单的答案是: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)