vendredi 21 juillet 2017

A thing delegating to lots of things - is this a design pattern or convention?

I am assuming the approach I'm using below is probably some kind of known design pattern in the Python world (and perhaps elsewhere), but I do not know what it is called in order to search for information and best-practices.

Cliffs notes version: I have some object, and it contains references to many other objects. Member access is delegated to those objects located at the top level in a certain order of resolution. Maybe this is called the "composition pattern"? But it doesn't really feel like a typical kind of tree-like structure to me because I want the access to the sub-members of the objects at the level-two objects (that are not containers of more objects- below these are Master, and Info) via the top level to basically be invisible.

Here is a simplified version of the object structure.

# Object format
+ Object
    + Master object
    + Group objects
        + Group obj1
        + Group obj2
        + etc
    + Info object
    + Node objects
        + Node obj1
        + Node obj2
        + etc
    + Element objects
        + Element obj1
        + Element obj2
        + etc
    + Boundary objects
        + Boundary obj1
        + Boundary obj2
        + etc

Each of these objects are a simple nameduple, with fields and default values. I have implemented Object using something like the code below (not a full representation).

from . import file_parser

class Object():
    def __init__(self, objtuple):
        (self.Master, self.Group,
        self.Info, self.Nodes,
        self.Elements, self.Boundaries) = objtuple
    @classmethod
    def from_file(cls, line_seq):
    '''Construct an instance using a file-like sequence
    file_parser produces a named_tuple in the form of:
    ObjectNT(Master, Group, Info, Nodes, Elements, Boundaries)'''
        objnt = file_parser(line_seq)
        obj = cls(objnt)
        return obj
    def __getattr__(self, attr):
        for member in (self.Master, self.Info):
            try:
                return getattr(member, attr)
            except AttributeError:
                pass

Aucun commentaire:

Enregistrer un commentaire