oop - Python - typechecking OK when error wouldn't be thrown otherwise? -
i have python classes that, if simplified, like:
class base: def __init__(self, v): self.value = v def dothings(self): print "doing things." def domorethings(self): print "doing more things." def combine(self, b): self.value += b.value class foo(base): def showvalue(self): print "foo value %d." % self.value class bar(base): def showvalue(self): print "bar value %d." % self.value the base class contains methods (represented above dothings , domorethings) implement functionality common both foo , bar subclasses. foo , bar subclasses differ in how interpret value field. (above, differ show when printing it, in actual application, several other things more complicated.) base can thought of "abstract": users ever work foos , bars. base exists home code common subclasses.
the method want ask combine, lets take 2 of these objects , make third. because foo , bar interpret value differently, doesn't make sense combine 2 subclasses of different types: can combine 2 foos foo or 2 bars bar not foo , bar. so, procedure combine same subclasses, makes sense have factored out , defined in 1 place.
i signal error if user tries combine 2 incompatible objects, don't see way without introducing ugly typechecks. practice this? or should usual thing , not check, document issue, , assume user won't try use combine in way wasn't intended, though such use appear "succeed" , return garbage object instead of raising error?
thank help.
i see several approaches here:
don't check , trust user right thing. might appropriate or dangerous, depending on situation.
check type. right looks ugly, easiest thing.
don't have
value, name them way intended have (pressure,temperature) , let them combine themselves.same 3, additionally have subclasses have
propertymaps accesses.valuerespective "real" value variable. way, can keep .__init__(),.combine()have done every subclass.same 4, don't use
property, self-crafted descriptor. in this answer, show how done.
Comments
Post a Comment