Reputation: 9766
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
Reputation: 5138
ex:
import repositories
mol = repositories.MoleculeRepository.FromFile('toto')
Upvotes: 0
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