pythonclassdesign-patternsstatic-methods

module with classes with only static methods


I have a Python module that contains a number of classes, each representing a particular physical material with its properties (e.g., density, specific heat). Some of the properties are just float members of the class, but many depend on some parameter, e.g., the temperature. I implemented this through @staticmethods, i.e., all of the classes look like

class Copper:
    magnetic_permeability = 1.0

    @staticmethod
    def density(T):
        return 1.0 / (-3.033e-9 + 68.85e-12*T - 6.72e-15*T**2 + 8.56e-18*T**3)

    @staticmethod
    def electric_conductivity(T, p):
        return 1.0141 * T**2 * p

    @staticmethod
    def specific heat(T):
        return # ...


class Silver:
    # ...

class Argon:
    # ...

# ...

The Classes thus merely act as containers for all the data, and the abundance of @staticmethods has me suspecting that there may be a more appropriate design pattern for this use case.

Any hints?


Solution

  • You could name your module copper and create all of these as module level functions, then import copper; copper.density(0).

    But what if someone does from copper import density, and you also have a module called cobalt and another called carbon and another called chlorine etc., all with their own density functions? Uh oh.

    Since we're all consenting adults here, you can document this and expect your users to know well enough to import just the module. Or you can take your approach; in this case, I would consider putting all of your elements in one module called elements, then the user can from elements import Copper. Static methods would then be appropriate.