Conflicting needs for __init__ method

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Mon Jan 15 05:00:14 CET 2007


On Mon, 15 Jan 2007 14:43:55 +1100, Steven D'Aprano wrote:

>> Of course, none of this really has anything to do with rational
>> numbers.  There must be many examples of classes for which internal
>> calls to __init__, from other methods of the same class, require
>> minimal argument processing, while external calls require heavier and
>> possibly computationally expensive processing.  What's the usual way
>> to solve this sort of problem?
> 
> class Rational(object):
>     def __init__(self, numerator, denominator):
>         print "lots of heavy processing here..."
>         # processing ints, floats, strings, special case arguments, 
>         # blah blah blah...
>         self.numerator = numerator
>         self.denominator = denominator
>     def __copy__(self):
>         cls = self.__class__
>         obj = cls.__new__(cls)
>         obj.numerator = self.numerator
>         obj.denominator = self.denominator
>         return obj
>     def __neg__(self):
>         obj = self.__copy__()
>         obj.numerator *= -1
>         return obj


Here's a variation on that which is perhaps better suited for objects with
lots of attributes:

    def __copy__(self):
        cls = self.__class__
        obj = cls.__new__(cls)
        obj.__dict__.update(self.__dict__) # copy everything quickly
        return obj




-- 
Steven D'Aprano 




More information about the Python-list mailing list