Hi,
I'm having a really hard time with subclassing sympy.geometry.line.Line. I want to have an object that has access to all of the great methods that sympy.geometry.line.Line provides, but with some extra methods and properties I need to define. In general I think my question could be extended to: How to subclass any class that uses __new__ as some sort of factory function for choosing which type of object to create...
Here's my small test code, on python 2.7 / sympy 1.1:
from __future__ import print_function
from sympy.geometry.line import Line
class MyClass(Line):
def __new__(cls, p1, p2):
return super(MyClass, cls).__new__(cls, p1, p2)
def __init__(self, p1, p2):
print('__init__ called')
self._p1 = p1
self._p2 = p2
def my_method(self):
print('my_method called')
m = MyClass((0, 0), (1, 1))
print(m)
>>> Line2D(Point2D(0, 0), Point2D(1, 1))print('Type of m: {}'.format(type(m)))
>>> Type of m: <class 'sympy.geometry.line.Line2D'>
# A sympy.geometry.line.Line method
print('sympy.geometry.line.Line method:', m.contains((0, 0)))
>>> sympy.geometry.line.Line method: True
# A sympy.geometry.line.LinearEntity method
print('sympy.geometry.line.LinearEntity method:', m.arbitrary_point())
>>> sympy.geometry.LinearEntity method: Point2D(t, t)
# my method
print('My method:', m.my_method())
>>> Traceback (most recent call last):
>>> File "test.py", line 31, in <module>
>>> print('My method:', m.my_method())
>>> AttributeError: 'Line2D' object has no attribute 'my_method'
The trouble is, I don't get access to any methods, properties or attributes I define in MyClass, since Line.__new__ doesn't even return a Line instance. MyClass.__init__ never gets called. I don't get a MyClass instance back.
By looking at sympy's source code, I thought all I had to do was override Line's __new__, but apparently that isn't working.
Thanks for any help!
Vincent