Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

python - How to use "lambda" as input inside of a class

I want to use lambda as an input for a class function named Integrator. Inside of the Integrator class, the object should be called based on the current state. I do not know how to introduce these objects to the Integrator class. Could you please tell me how can I call a created object inside of another class? Here is the main simulation program:

# create LJ force object
lj_object = LennardJones(self.sigma, self.epsilon, self.compmethod, self.r_cut, self.box_len)

# create spring force object
sp_object = InterMolecularForce (self.oh_len, self.k_b, self.tet_eq, self.k_tet)

# create Integrator object
integrator_object = Integrator (O_mass, H_mass)

for i in range (grid.shape[0]-1) :

        timespan = (grid [i], grid [i+1])                       

        lj_force =lj_object (new_postate)

        sp_force = sp_object(new_postate)

        new_postate[i+1], new_velocity[i+1] = integrator_object (new_postate, new_velocity, lambda new_postate: lj_object (new_postate) + sp_object(new_postate), timespan)

return new_postate, new_velocity

The integrator is :

# calculate half step momenta
momenta_half_step = diag_mass * velocity + (force * (timespan[1] - timespan[0]) / 2)
position_full_step = posate + (timespan[1] - timespan[0]) * np.dot (inv(mass_matrix), momenta_half_step) 

# calculate forces
lj_force = lj_object (position_full_step)
spring_force = sp_object(position_full_step)
force = lj_force + spring_force

momenta_full_step = momenta_half_step + ( timespan[1] - timespan[0] ) * force / 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I have a strong feeling that I have missed the point here. But without attempting any of the complex applied mathematics your code is doing, here is a simple, bare-bones approach to passing a function defined in a lambda statement and passing it to a class to use.

class Operation:
    def __init__(self, operator):
        self.operator = operator
    def compute(self, *operands):
        return self.operator(operands[0], operands[1])


>>> addition=Operation(operator=lambda a,b: a+b)
>>> multiplication=Operation(operator=lambda a,b: a*b)
>>> addition.compute(3,5)
8
>>> multiplication.compute(3,5)
15

This is deliberately simplified and contrived: it does no type checking, it neither handles nor rejects operators that are not dyadic, and all in all it is not very useful. Its only purpose is to show how to call the function that was passed into the class, which seems to be the fundamental point of your question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...