Ger
Ger

Reputation: 9766

Python object creation from a function

My problem might be more linked to OOP than python. I wrote a class in order to describe a molecule and then I wrote a function in order to create a molecule object from a specific file format : fromFILE. Thus, for example, I do the following when I use my class :

import mymodule
mol = mymodule.fromFILE("toto")
mol.method()
...

My question is what is the good way for organizing things. Should the function fromFILE() be a part of the class or not and if yes what is the best way to write this ?

Until now, I just put the class and the functions which can be used to create this class into the same module but I do not know if this is the best way to do that.

Upvotes: 2

Views: 134

Answers (2)

Mgetz
Mgetz

Reputation: 5138

  1. Does the behavior of your molecule care about file IO? Probably not, this suggests that the molecule is an entity and should be persistence ignorant. At the same time it needs to enforce its own business logic.
  2. Is the information needed to construct a molecule itself business logic? if so then you may want to consider using either the repository pattern or the factory pattern, or a combination of the two (what I would do)

ex:

import repositories
mol = repositories.MoleculeRepository.FromFile('toto')

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124968

You can make it a class method:

class Molecule(object):
    # ...

    @classmethod
    def fromFile(cls, filename):
        data = # ... parse data from filename ...
        return cls(data)

This has the added advantage that subclasses can simply inherit it, or override it to adjust what the method does (including calling the original parent implementation). It provides an alternative class factory:

import mymodule

mol = mymodule.Molecule.fromFile('toto')

neatly grouping this factory with the class itself.

Upvotes: 8

Related Questions