On 13.02.15 05:41, Ethan Furman wrote:
So there are basically two choices:

1) always use the type of the most-base class when creating new instances

    pros:
      - easy
      - speedy code
      - no possible tracebacks on new object instantiation

    cons:
      - a subclass that needs/wants to maintain itself must override all
        methods that create new instances, even if the only change is to
        the type of object returned

2) always use the type of self when creating new instances

    pros:
      - subclasses automatically maintain type
      - much less code in the simple cases [1]

    cons:
      - if constructor signatures change, must override all methods which
        create new objects

And switching to (2) would break existing code which uses subclasses with constructors with different signature (e.g. defaultdict).

The third choice is to use different specially designed constructor.

class A(int):

class A(int):
... def __add__(self, other): ... return self.__make_me__(int(self) + int(other))

... def __repr__(self):
...         return 'A(%d)' % self
...
A.__make_me__ = A
A(2) + 3
A(5)
class B(A):
...     def __repr__(self):
...         return 'B(%d)' % self
...
B.__make_me__ = B
B(2) + 3
B(5)

We can add special attribute used to creating results of operations to all basic classes. By default it would be equal to the base class constructor.

_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
https://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
https://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to