I’m studying python through the paid online course and i got an error by typing following codes while studying module and pakages.
class Fibonacci:
def __init__(self, title="fibonacci"):
self.title = title
def fib(n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
def fib2(n):
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a + b
return result
and the def shows an error like "def Method should have "self" as first argument". do you know why am i having an error? i think my code should be okay, and when i try to run it though my friends laptop(window) it works well btw, I’m using mac os. sorry I’m just new to python .. :) click to see the error here
----- edited ----------------- thanks for the comments! and i have edited like the pictureedited code and it has no error! :)
but when i try to call the function, has an error like TypeError: fib() missing 1 required positional argument: 'n'
from pkg.fibonacci import Fibonacci
Fibonacci.fib(100)
see the error message error message2
Not sure if the fib / fib2 is the class method.
if they are, you may add self in the object parameter, as
def fib(self, n)
Then you may call the method like:
f = Fibonacci()
f.fib(5)
The self parameter is referring to the class object, so that you may use self attributes in the class method, in you case, you may have
def fib(self, n):
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a + b
print()
print(self.title)