Hi Joakim,
You seem to be taking the very view that inheritance means nothing but reuse
of definitions. This view, however, is not accepted in any principled approach
to OOP that I'm aware of.
On Thursday 03 March 2016 19:58:30 Joakim Saario wrote:
> Yes, Child would be "unrelated" in the sense that it doesn't have any
> connections to its parent
> other than the fields. Is the problem that this uses the inheritance
> semantics?
>
Mostly, yes; inheritance encodes an "is-a" relation between concepts, which
you seem to disregard completely.
> Python doesn't offer a mechanism for accessing parent objects or vice
> versa, this is something you will have to implement yourself if you want it.
> So I don't see how this would be surprising for any python programmers.
>
There is a difference in terms here: Aymeric referred to "casting into
parents", you are referring to "accessing parent objects". The point is that
the parent object is not some distinct entity that you need to navigate to,
but just a different way to look at the same instance.
Python does support a form of this casting to a parent with super().
> The relational inheritance can actually cause data corruption when you
> don't expect the parents data to be a superset of the childrens data.
If you don't expect this, your understanding of inheritance is at odds with
the rest of the world's.
> However, the the parent's
> definition may still be
> a superset of the childrens definition, if you don't override any fields.
>
> As an example of this, consider:
>
> class 3DTable(models.Model):
> width = models.IntegerField()
> height = models.IntegerField()
> depth = models.IntegerField()
>
> class 4DTable(3DTable):
> some_other_dimension = models.IntegerField()
>
> Now, of course this depend of what a 4DTable is. It may NOT even be
> projectible in the 3D space at all, at least not in a sensible way. So it s
> houldn't be presented as if it were.
>
If so, it shouldn't be a subclass of 3DTable.
> As for the definition, they are mostly the same, 4DTable adds another
> dimension. It should in this case inherit the definition only.
>
If the two classes share nothing but a set of fields -- and these fields do not
make sense as some independent concept that is common to the two classes --
then the best design is to keep them completely separate (this is true even if
they are not Django models), because they are likely to evolve independently.
If the shared part does make sense as a full concept, but you still intend the
two classes to be unrelated, then that concept should be defined as a common
parent class (or abstract model):
class BaseDimensions(models.Model):
width = models.IntegerField()
height = models.IntegerField()
depth = models.IntegerField()
class Meta:
abstract = True
class 3DTable(BaseDimensions):
pass
class 4DTable(BaseDimensions):
some_other_dimension = models.IntegerField()
HTH,
Shai.