Reputation: 363
I am writing a program in Python 3 that creates objects from a class, and from these objects I can run some calculations. However, when I instantiate my object and try to run it's methods, I get the following error: TypeError: method1() missing 1 required positional argument: 'index'
. Here is an example of the code:
class Foo:
def __init__(self, var1, var2, var3):
"""var1 and var2 are lists"""
self.var1 = var1
self.var2 = var2
self.var3 = var3
def method1(self, index):
return self.var3 * (self.var1[index] + self.var2[index])
def run_calculation(self):
for i in range(1,10):
self.var1.append(Foo.method1(i))
self.var2.append(Foo.method1(i))
When I try to run this code like so:
a = Foo([1],[2],3)
a.run_calculation()
I get the error described above. method1
always gets passed the argument necessary when it is called during run_calculation
, so I don't see the problem. Thank you in advance!
Upvotes: 0
Views: 422
Reputation: 853
you are calling it like class method. here is the correct version.
class Foo:
def __init__(self, var1, var2, var3):
"""var1 and var2 are lists"""
self.var1 = var1
self.var2 = var2
self.var3 = var3
def method1(self, index):
return self.var3 * (self.var1[index] + self.var2[index])
def run_calculation(self):
for i in range(1, 10):
self.var1.append(self.method1(i))
self.var2.append(self.method1(i))
print(self.var1, self.var2)
a = Foo([1,2], [3,4], 5)
a.run_calculation()
Upvotes: 0
Reputation: 1014
The problem here is that you call that method as a static one. you need to use self instead of Foo. in run_calculation()
class Foo:
def __init__(self, var1, var2, var3):
"""var1 and var2 are lists"""
self.var1 = var1
self.var2 = var2
self.var3 = var3
def method1(self, index):
return self.var3 * (self.var1[index] + self.var2[index])
def run_calculation(self):
for i in range(1,10):
self.var1.append(self.method1(i)) # notice the self here
self.var2.append(self.method1(i)) # notice the self here
Upvotes: 1