given these classes forming flexible tree:
class elementbase(object): pass class form(elementbase): pass class textinput(elementbase): pass class datetimeinput(elementbase): pass class numberinput(elementbase): pass if element inside form should able find said form. since common case elements (in case third of elements inheriting elementbase need it) feature belongs elementbase. directly leads circular dependency since way came this:
def get_parent_form(self, compo): if isinstance(compo, form): return compo if not hasattr(compo, 'container_compo'): return none return self.get_parent_form(compo.container_compo) how do properly?
@jonrsharpe talked in comments i'll elaborate more:
your structure as-is doesn't make sense object hierarchy. form partly made of composition of *input objects, of can grouped common attribute of being elements , having form parent. distinguishable behavior form itself, (at least can tell) forms cannot nested inside 1 another, , distinguishable other elementbase inheriting objects because account third of them exhibit behavior.
because have large group of objects exhibiting common behavior in separable way, reasonable thing implement parent class implements behavior, , have necessary inputs inherit class.
you have elementbase -> form , elementbase -> input -> textinput, etc.
this isn't "hacky" because can delineate behavior , make logical groupings of classes exhibit it. consider more hacky try shoehorn logic elementbase when 2/3 of classes inherit don't display behavior.
also note if did forminput talked in comments, forminput wouldn't have reside in form's module describes own group of objects happen have relation form.
there ways re-write whole system allow things arbitrary form-within-form nesting, etc. end rather radically different api. one thing might want consider right now, though, why you're having child elements access parent forms in first place. general oop rule want parents accessing children, because otherwise objects aren't encapsulating specific behavior , properties. in example, i'd expect textinput "own" characters inside of it, why need manipulate in form? why can't form grab text input when needs to?
you might want @ other code bases have done similar project ideas on how model data. recommend django-rest-framework particularly example of form-input (in case, serializer-field) implementation. serializers forms because they're careful in way access data, can have serializers inherit fields , make them arbitrarily nestable. , it's pretty code, too.
Comments
Post a Comment