[英]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__
上y
做y[0]
而引发异常。
Moreover, there is a syntax error as you assign the result to return
. 此外,在将结果分配给
return
存在语法错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.