【发布时间】:2014-12-01 02:17:09
【问题描述】:
我的目标是减少我创建的类中的一些冗余。我已将问题简化为一个非常简单的示例
我现在的班级
class BigNumbers(object):
def __init__(self, big_number):
self.number = big_number
@classmethod
def make_with_sums(cls, sum_to):
fin_num = 0
for i in range(1, sum_to):
fin_num += i
return cls( fin_num )
@classmethod
def make_with_product(cls, mul_to):
fin_num = 1
for i in range(1, mul_to):
fin_num *= i
return cls( fin_num )
我想要的班级(DNRY)
class dnryNumbers(object):
def __init__(self, big_number):
self.number = big_number
@classmethod
def _make_with_helper(cls, make_meth, fin_num):
method_dict = {'sum': lambda x, y: x + y,
'prod': lambda x, y: x * y
}
var = 0
for i in range(1, fin_num):
var = method_dict[make_meth](var, i)
return cls( var )
def make_with_sums(self, sum_to):
return self._make_with_helper( 'sum', sum_to )
def make_with_product(self, mul_to):
return self._make_with_helper('prod', mul_to )
我的目标是使用与使用 BigNumbers 类时相同的函数调用,例如:
In [60]: bn = BigNumbers.make_with_product(10)
In [61]: bn.number
Out[61]: 362880
-- 或者--
In [63]: bn = BigNumbers.make_with_sums(10)
In [64]: bn.number
Out[64]: 45
但是当前的功能不起作用:
In [65]: bn = dnryNumbers.make_with_product(10)
TypeError: unbound method make_with_product() must be called with dnryNumbers instance as first argument (got int instance instead)
【问题讨论】:
-
您还必须将这些方法设为类方法并调用 cls._make_with_helpers(args)
-
您的示例似乎存在一些问题:例如,dnryNumbers.make_with_product 方法不是类方法。这是故意的吗?