Iteration for Factorials

marek.rocki at wp.pl marek.rocki at wp.pl
Wed Oct 24 18:19:30 EDT 2007


Tim Golden napisa (a):

> It's only a moment before the metaclass and
> the Twisted solution come along. :)

I couldn't resist. It's not as elegant as I hoped, but hey, at least
it memoizes the intermediate classes :-)


class fact_0(object):
	value = 1

class fact_meta(object):
	def __new__(cls, name, bases, attrs):
		n = attrs['n']
		class_name = 'fact_%i' % n
		try:
			return globals()[class_name]
		except KeyError:
			new_class = type(class_name, bases, {})
			new_class.value = n * fact(n - 1).value
			new_class.__str__ = lambda self: str(self.value)
			globals()[class_name] = new_class
			return new_class

class fact(object):
	def __new__(self, n_):
		class spanish_inquisition(object):
			__metaclass__ = fact_meta
			n = n_
		return spanish_inquisition()

print fact(5)
print fact(3)
print fact(1)




More information about the Python-list mailing list