Simple But Too Many Positional Arguments For Method Call
Solution 1:
The first argument of a method is self
, which refers to the object the method is being called on. If, as it appears, you wish to pass an argument (n
, it looks like), you need to include that in the method's signature.
Solution 2:
This function takes one argument self
, but this line: self.fib(self.n - 1)
attempts to pass 2: self
and self.n - 1
.
Solution 3:
When u first call fib() in
print(first_func.fib())
you pass no args except the implicit self. in the next call you pass 1 arg which makes it 2 (including the implicit self)
self.fib(self.n - 1)
This provides the TypeError: fib() takes 1 positional argument but 2 were given
about the Fibonacci, a simpler implementation :
def fib(n):
if n==0 or n==1:
return1else:
return (fib(n-1) + fib(n-2))
Solution 4:
A type error can mean many things. In this case it means that you have passed too many arguments into a function. It looks like you are calling self.fib with a parameter. You have defined it only with self as a parameter. From the way you have written your code, it seems that you think that you need to pass self as an argument. The truth is that it is an invisible parameter that is already passed when you call the function.
Do something like this:
classmath_func:
def__init__(self, '''...'''):
#...deffib(self):
#...
self.n = self.n - 1
self.fib()
or
classmath_func:
def__init__(self, '''...'''):
#...deffib(self):
#...
self.fib2(self.n -1)
deffib2(self, n: int):
#...#same thing as fib with slight changes
or
classmath_func:
def__init__(self, '''...'''):
#...deffib(self, n: int):
#...
self.fib(self.n - 1)
defgetN(self):
return self.n
fib = math_func('''...''')
print(fib.fib(fib.getN())
Solution 5:
You need to include n as fib's agrument
deffib(self, n):
...
Also a little addition: If you define recursive functions you should consider using lru_cache decorator for performance improvement.
from functools import lru_cache
...
@lru_cache(500) # 500 is the cache sizedeffib(self, n):
...
Post a Comment for "Simple But Too Many Positional Arguments For Method Call"