简体   繁体   English

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

[英]Passing a class instance method to another function in Python (2.7)

sorry if the title does not make sense, I am relatively new to this. 抱歉,如果标题没有意义,我对此还比较陌生。 This is my code: 这是我的代码:

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))

But I get the error TypeError: 'int' object has no attribute '__getitem__' 但是我收到错误TypeError: 'int' object has no attribute '__getitem__'

My question is how do I pass this function which is a method of my class instance into another function. 我的问题是如何将这个作为类实例方法的函数传递给另一个函数。 If I define the function outside the class and pass it to another function this works but is not what I want. 如果我在类之外定义该函数并将其传递给另一个函数,则可以,但这不是我想要的。 Thanks! 谢谢!

Edit: The typo return = y[0]*self.V0 has been corrected. 编辑:错字return = y[0]*self.V0已得到纠正。

What's generating TypeError: 'int' object has no attribute '__getitem__' is this: 产生TypeError: 'int' object has no attribute '__getitem__'是这样的:

y[0]

This is because at this point, y 's value is 1 , an integer, and y[0] is acting as if y is a list or string ( __getitem__ is the method called to get items in lists). 这是因为在这一点上, y的值是1 (一个整数),并且y[0]的作用就像y是列表或字符串( __getitem__是用于获取列表中项目的方法)。 If y were a list (eg y = [1] ), it'd work fine. 如果y是一个列表(例如y = [1] ),它将很好地工作。

If you remove the [0] , you're in business: 如果删除[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))

There is an error in your code. 您的代码中有错误。 You are passing 1 as the first argument to velocity_field which in turn passes it to LHS as the second argument ( y ). 您将1作为第一个参数传递给velocity_field ,然后将其作为第二个参数( y )传递给LHS Lastly, you call __getitem__ on y by doing y[0] , and that raises the exception. 最后,你调用__getitem__yy[0]而引发异常。

Moreover, there is a syntax error as you assign the result to return . 此外,在将结果分配给return存在语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM