python - 将类实例方法传递给 Python 中的另一个函数 (2.7)

标签 python

如果标题没有意义,我很抱歉,我对此比较陌生。这是我的代码:

class MeanFlow:
    def __init__(self, V0=1):
        self.V0 = V0
    def LHS(self, t, y):
        return y[0]*self.V0


def velocity_field(w,f):
    z = 0 # dummy 
    u = f(z,w).real
    v = -1*f(z,w).imag 
    return u, v

w0 = 1
mean = MeanFlow()
dwdz = mean.LHS
print(velocity_field(w0, dwdz))

但我收到错误 TypeError: 'int' object has no attribute '__getitem__'

我的问题是如何将这个函数(我的类实例的一个方法)传递给另一个函数。如果我在类外部定义函数并将其传递给另一个函数,这会起作用,但不是我想要的。谢谢!

编辑:拼写错误 return = y[0]*self.V0 已更正。

最佳答案

生成 TypeError: 'int' object has no attribute '__getitem__' 的原因是这样的:

y[0]

这是因为此时 y 的值为 1,一个整数,而 y[0] 就好像y 是一个列表或字符串(__getitem__ 是为获取列表中的项目而调用的方法)。如果 y 是一个列表(例如 y = [1]),它就可以正常工作。

如果您删除 [0],则说明您在做生意:

class MeanFlow:
    def __init__(self, V0=1):
        self.V0 = V0
    def LHS(self, t, y):
        return y*self.V0


def velocity_field(w,f):
    z = 0 # dummy 
    u = f(z,w).real
    v = -1*f(z,w).imag 
    return u, v

w0 = 1
mean = MeanFlow()
dwdz = mean.LHS
print(velocity_field(w0, dwdz))

关于python - 将类实例方法传递给 Python 中的另一个函数 (2.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22808764/

相关文章:

python - 如何修复 : 'TypeError: expected string or bytes-like object' when doing unit test on a views. py 函数

python - NumPy 如何实现其复数字面量?

python - cv2.imshow 崩溃 - libc++abi.dylib : terminating with uncaught exception of type NSException

python - 类型错误 : keys() takes no arguments (1 given)

python - python中的2d列表到3d列表

python - Pandas 创建完美的面板数据,根据条件附加空行

python - 如何使用 Selenium for Python 在另一个选项卡中打开图像?

python - 如何在 django admin 中创建一个自动填充和自动递增的字段

python - 使用 Python 3(而非 Python 2)下载时 Zip 文件损坏

python - Pandas 数据帧 : how to summarize columns containing value