python - Class inheritance: should constructors be compatible? case of multiple inheritance? -
python - Class inheritance: should constructors be compatible? case of multiple inheritance? -
this question has reply here:
should constructors comply liskov substitution principle? [closed] 3 answersone of recommended principles of object-oriented programming liskov substitution principle: subclass should behave in same way base of operations class(es) (warning: not right description of liskov principle: see ps).
is recommended apply constructors? have python in mind, , __init__()
methods, question applies object-oriented language inheritance.
i asking question because useful have subclass inherit 1 or more classes provide nice default behavior (like inheriting dictionary, in python, obj['key']
works objects of new class). however, not natural or simple allow subclass used dictionary: nicer constructor parameters relate specific user subclass (for instance, class represents set of serial ports might want behave dictionary ports['usb1']
beingness usb port #1, etc.). recommended approach such situation? having subclass constructors compatible of base of operations classes, , generating instances through object mill function takes simple, user-friendly parameters? or writing class constructor set of parameters cannot straight given constructor of base of operations classes, more logical user perspective?
ps: misinterpreted liskov principle, above: sven's comment below points out fact objects of subclass should behave objects of superclass (the subclass not have behave superclass; in particular, constructors not have have same parameters [signature]).
as requested, post reply has been comment.
the principle defined in linked wikipedia article reads "if s subtype of t, objects of type t may replaced objects of type s". not read "a subclass should behave in same way base of operations class(es)". difference of import when thinking constructors: wikipedia version talks objects of subtype, not type itself. object, constructor has been called, principle doesn't apply constructors. how apply it, , ways seems applied in standard lib (e.g defaultdict
, dict
).
constructors in multiple inheritance can't discussed in language-agnostic way. in python, there 2 approaches. if inheritance diagram includes diamond patterns , need create sure constructors called once, should utilize super()
, follow pattern described in section "practical advice" of raymond hettinger's article python's super()
considered super. if don't have diamonds (except ones including object
), can utilize explicit base of operations class calls base of operations class constructors.
python oop constructor lsp
Comments
Post a Comment