Conflicting needs for __init__ method
Ziga Seilnacht
ziga.seilnacht at gmail.com
Sun Jan 14 19:49:00 EST 2007
Mark wrote:
[a lot of valid, but long concerns about types that return
an object of their own type from some of their methods]
I think that the best solution is to use an alternative constructor
in your arithmetic methods. That way users don't have to learn about
two different factories for the same type of objects. It also helps
with subclassing, because users have to override only a single method
if they want the results of arithmetic operations to be of their own
type.
For example, if your current implementation looks something like
this:
class Rational(object):
# a long __init__ or __new__ method
def __add__(self, other):
# compute new numerator and denominator
return Rational(numerator, denominator)
# other simmilar arithmetic methods
then you could use something like this instead:
class Rational(object):
# a long __init__ or __new__ method
def __add__(self, other):
# compute new numerator and denominator
return self.result(numerator, denominator)
# other simmilar arithmetic methods
@staticmethod
def result(numerator, denominator):
"""
we don't use a classmethod, because users should
explicitly override this method if they want to
change the return type of arithmetic operations.
"""
result = object.__new__(Rational)
result.numerator = numerator
result.denominator = denominator
return result
Hope this helps,
Ziga
More information about the Python-list
mailing list