Friday, 29 January 2021

How have FreeCAD screwed inheritancy from a python class?

I would like to inherit from Vector, a FreeCAD python class.

In the following test code, I either use my own Vector class or import the Vector class from FreeCAD. It works fine with my own Vector class, but prints a vector of zeroes and then crashes with - 'Base.Vector' has no attribute 'extra', implying the constructor of ExtraVector has been bypassed and ExtraVector is just a Vector, when using the FreeCAD Vector.

(I suspect that the FreeCAD vector is a wrapper around C code)

  1. What have FreeCAD done? How do you mess with a python class to give it this behavior?

  2. How do I get around it? Inheritance is the best solution to my problem. Composition means writing a lot more code, and I don't like WET.

# ---------------------------------------------------

# Vector is either defined in this file or imported
# (comment out to swap over)

#from FreeCAD import Vector  # Probably a wrapper around C code

class Vector :  
  def __init__ ( self, x, y, z ) :
    self.x = x
    self.y = y
    self.z = z

# ---------------------------------------------------

class ExtraVector ( Vector ) :
  def __init__ ( self, x, y, z, extra ) :
    super().__init__ ( x, y, z )
    self.extra = extra

def Test ( ) :

  evect = ExtraVector ( 1, 2, 3, 4 )

  print ( "x = ", evect.x,  " y = ", evect.y, " z = ", evect.z )
  print ( "e = ", evect.extra )

Test()

When my Vector class is used (FreeCAD Vector commented out), output is :-

x =  1  y =  2  z =  3
e =  4

When FreeCAD Vector is used (my Vector commented out), output is:-

x =  0.0  y =  0.0  z =  0.0
Traceback (most recent call last):
  File "ExtraVector.py", line 28, in <module>
    Test()
  File "ExtraVector.py", line 26, in Test
    print ( "e = ", evect.extra )
<class 'AttributeError'>: 'Base.Vector' object has no attribute 'extra'



from How have FreeCAD screwed inheritancy from a python class?

No comments:

Post a Comment