Home > Enterprise >  Storing Functions with parameter arguments as instances in Classes in Python
Storing Functions with parameter arguments as instances in Classes in Python

Time:04-12

I am trying to set up a class where I can define a function G(.) which can have any number of parameters. The code below shows a default setting for G(rij), which is then usable in get_k() and get_y(). However, I now define a second function called G_ln(rij, a, c, s) which takes in an arbitrary number of parameters. The class has the variable "a" already defined. How would one structure this code in the best manner, such that the arguments are either stored in the class or passable in to the functions for an arbitrary G.

The code below naturally yields an error as "a", "c" and "s" are not defined. This is only a sample of the full code, where get_y() and get_k() are used in other functions as well, so I want the arguments to be passed in, in a general manner.

class Tree:
    def __init__(self, a, sigma, j, dt):
        self.a = a
        self.sigma = sigma
        self.j = j
        self.dt = dt
        
    def set_G(self, G=lambda r: np.where(r < -0.01, 0.2, 0)):
        self.G = G
       
    def get_k(self, rij, ri0):
        t1 = (self.G(rij) - self.G(ri0)) * self.dt / self.dx
        return np.floor(self.j   t1   1/2)
    
    def get_y(self, rij, ri0):
        k = self.get_k(rij, ri0)
        t1 = (self.G(rij) - self.G(ri0)) * self.dt / self.dx
        return self.j   t1 - k
  
def G_ln(rij, a, c, s):
    if rij < np.log(s):
        val = -a * c * x / (np.exp(x)   c - s)
    else:
        val = - a * x
    return val    

a = 0.25
s = 0.02
sigma = 0.3
c = 0.03
lda = -0.12

rij = np.array([-0.01310713, -0.00444688,  0.00421338])
ri0 = rij[1]

test = Tree(a, sigma, j = [-1, 0, 1], dt=0.25)
test.set_G(G=G_ln)

k = test.get_k(rij, ri0)
y = test.get_y(rij, ri0)

Perhaps something along these lines is a solution? However, there does not necessarily need to be any additional arguments.

def set_G(self, G, args):
    self.G = lambda rij: G(rij, *args)

CodePudding user response:

Rather than pushing this complexity into your Tree class, I would just bind the extra arguments when G is set:

test.set_G(lambda r: G_ln(r, a, c, s))

on the theory that if the values are only used by G, G should be the thing that keeps track of them.

  • Related