#coding:utf-8 def new(cls, *args, **kwargs): ''' 若cls是函数,则调用之;若cls是类型,则生成一个cls类型的对象 ''' return cls(*args, **kwargs) class Number(object): pass class IntegralNumber(int, Number): ''' 整数类,自定义了一个toInt函数,可以把自己转换为一个int型。 折腾了半天,x=IntegralNumber(3) 最终就是x=3 ''' def toInt(self): return new (int, self) class InternalBase(object): ''' 按设计者的意思,每个数学系统(StandardMathematicsSystem)应该有个基数 该类就是来表示这个基数的,这里的StandardMathematicsSystem的基数是2 ''' def __init__(self, base): self.base = base.toInt() def getBase(self): return new (IntegralNumber, self.base) class MathematicsSystem(object): ''' MathematicsSystem实现了一个最简单的单例类,需通过getInstance获取实例 ''' def __init__(self, ibase): Abstract @classmethod def getInstance(cls, ibase): try: cls.__instance except AttributeError: cls.__instance = new (cls, ibase) return cls.__instance class StandardMathematicsSystem(MathematicsSystem): ''' 用于计算的数学系统 ''' def __init__(self, ibase): ''' 验明基数 ''' if ibase.getBase() != new (IntegralNumber, 2): raise NotImplementedError self.base = ibase.getBase() def calculateFactorial(self, target): ''' 实际干活 ''' result = new (IntegralNumber, 1) i = new (IntegralNumber, 2) while i <= target: result = result * i i = i + new (IntegralNumber, 1) return result print StandardMathematicsSystem.getInstance(new (InternalBase, new (IntegralNumber, 2))).calculateFactorial(new (IntegralNumber, 6)) #720