【问题标题】:How to use "lambda" as input inside of a class如何在类中使用“lambda”作为输入
【发布时间】:2021-04-21 05:47:58
【问题描述】:

我想使用lambda 作为名为@9​​87654322@ 的类函数的输入。在Integrator 类内部,应根据当前状态调用对象。我不知道如何将这些对象引入Integrator 类。 你能告诉我如何在另一个类中调用创建的对象吗? 下面是主要的模拟程序:

# 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

积分器是:

# 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

【问题讨论】:

  • 我觉得这个问题很难理解,因为代码告诉我们你的代码在做什么:这个问题没有清楚地解释你想要它做什么。问题是如何将 lambda 函数传递给类方法?
  • 是的。如何将 lambda 函数传递给类方法?
  • 打电话integrator_object时不是已经过去了吗?

标签: python numpy class dynamic


【解决方案1】:

我有一种强烈的感觉,我错过了这里的重点。但是,无需尝试您的代码正在执行的任何复杂的应用数学运算,这里有一个简单的、基本的方法来传递在 lambda 语句中定义的函数并将其传递给一个类以供使用。

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

这是故意简化和设计的:它不进行类型检查,既不处理也不拒绝非二元运算符,总而言之,它不是很有用。它的唯一目的是展示如何调用传递给类的函数,这似乎是您问题的基本点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 2020-09-22
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多