Is overriding a property's type in a Python sub-class pythonic?

Viewed 48

I have a python class (P) with a property x, which I use to store a single value in code that instantiates instances of P. Then, in a sub-class of class P (Q) I override (correct nomenclature?) x to instead store a list of values. This feels like just a case of making use of Python's dynamic typing. But is this Pythonic?

class P:
    def __init__(self,x):
        self.x = x

class Q(P):
    def __init__(self,x):
        self.x = [x]


>>> p = P(1)
>>> p.x
1
>>> q = Q(1)
>>> q.x
[1]
>>>
1 Answers

So it seems that using this approach isn't so Pythonic in that it breaks Liskov substitutability and the idea of least-surprise.

Related