Reputation: 1910
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__'
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.
Upvotes: 1
Views: 1590
Reputation: 1824
What's generating TypeError: 'int' object has no attribute '__getitem__'
is this:
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). If y
were a list (e.g. y = [1]
), it'd work fine.
If you remove the [0]
, you're in business:
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))
Upvotes: 3
Reputation: 2482
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
). Lastly, you call __getitem__
on y
by doing y[0]
, and that raises the exception.
Moreover, there is a syntax error as you assign the result to return
.
Upvotes: 2