Python supports LSP, does it?
Kay Schluehr
kay.schluehr at gmx.net
Thu Aug 11 17:06:06 EDT 2005
en.karpachov at ospaz.ru wrote:
> On Thu, 11 Aug 2005 01:19:19 +0100
> phil hunt wrote:
>
> > According to Wikipedia, the Liskov substitution principle is:
> >
> > Let q(x) be a property provable about objects x of type T. Then
> > q(y) should be true for objects y of type S where S is a subtype of T
> >
> > To me, this is nonsense. Under this definition any subtype must
> > behave the same as its parent type, becausde if it doesn't there
> > will be some q(y) that are different to q(x).
> >
> > But if it behaves the same, what's the point of having a subtype?
>
> It does not behave the same, it has the same properties.
Doesn't it?
"What is wanted here is something like the following substitution
property: If
for each object o1 of type S there is an object o2 of type T such that
for all programs P defined in terms of T, the behavior of P is
unchanged when o1 is substituted for o2 then S is a subtype of T."
Barbara Liskov, "Data Abstraction and Hierarchy" SIGPLAN Notices,
23,5 (May, 1988).
IOW if an arbitrary program P works with objects of type T and you
replace each object of type T by an object of type S and each P works
still the same way one can imply that S is a subtype of T.
It is a funny aspect of this definition that it doesn't work for
reflective programming languages. If you have access to properties AS
properties ( on the meta-level ) it is easy to break LSP. Preserving
LSP becomes a challenge or a requirement.
Example:
The statement
if type(obj) == T:
...
breaks LSP. One might say that that T has no subtypes at all. But since
T is arbitrary chosen no type in Python has a subtype in a strict
sense.
On the other hand this statement preserves LSP:
if isinstance(obj,T):
...
Therefore one can write programs that work as if LSP was valid and
subtypes indeed exist.
Kay
More information about the Python-list
mailing list