Search code examples
python-3.xclassdictionarychainingkeyword-argument

How can I correctly implement this example of using classes?


In the following example, one can choose constants to depend upon the context of a future situtation.

class Constants:
    SPEEDLIGHT = 3 * 10**8
    GRAVITY = 9.81

C = Constants()
print(C.GRAVITY)
>> 9.81

That was not too difficult because each quantity is a fixed constant. But suppose I want to do something similar for functions. In this first block of code below, I specify two distributions of integrable variable x and fixed parameters a and b.

class IntegrableDistribution:
    def Gaussian(x,a,b):
        cnorm = 1 / ( b * (2 * pi)**(1/2) )
        return cnorm * np.exp( (-1) * (x-a)**2 / (2 * b**2) )
    # Gaussian = Gaussian(x,a,b)

    def Lognormal(x,a,b):
        cnorm = 1 / ( b * (2 * pi)**(1/2) )
        return cnorm * exp( (-1) * (np.log(x)-a)**2 / (2 * b**2) ) / x
    # Lognormal = Lognormal(x,a,b)

I was trying to name the distributions so that they could be callable. That resulted in an error message, hence the commented out code above. In this next block of code, I am trying to use an input to select a distribution for integration (though I feel it is extremely inefficient).

Integrable = IntegrableDistribution()

class CallIntegrableDistribution:

    def Model():

        def Pick():
            """
            1 :   Gaussian Distribution
            2 :   Lognormal Distribution
            """
            self.cmnd = cmnd
            cmnd = int(input("Pick a Distribution Model:    "))
            return cmnd

        self.cmnd = cmnd

        if cmnd == 1:
            Distribution = Integrable.Gaussian
        if cmnd == 2:
            Distribution = Integrable.Lognormal

        return Distribution

OR ALTERNATIVELY

    cmnd = {
        1: Gaussian,
        2: Lognormal,
    }

I'm not really concerned with the problem of distributions; I'm only applying it to showcase my knowns and unknowns. What are some ways to properly do this or something similar/simpler using classes or dictionaries?


Solution

  • Use static methods:

    class IntegrableDistribution:
        @staticmethod
        def Gaussian(x,a,b):
            cnorm = 1 / ( b * (2 * pi)**(1/2) )
            return cnorm * np.exp( (-1) * (x-a)**2 / (2 * b**2) )
    
        @staticmethod
        def Lognormal(x,a,b):
            cnorm = 1 / ( b * (2 * pi)**(1/2) )
            return cnorm * exp( (-1) * (np.log(x)-a)**2 / (2 * b**2) ) / x
    

    And usage:

    some_result = IntegrableDistribution.Gaussian(1, 2, 3)
    another_result = IntegrableDistribution.Lognormal(1, 2, 3)