It says " AttributeError: 'int' object has no attribute 'Factorial' ", how could i tackle it? I want to use my generator in my function in the same class.
class a:
def __init__(self, n):
self.n = n
def Factorial(self):
res = 1
for i in range(1, self):
res *= i
yield res
def m(self):
s = []
for i in self.Factorial(self):
s.append(i)
return s
print(a.m(100))
CodePudding user response:
Here is a working version:
class a:
def __init__(self, n):
self.n = n
def Factorial(self):
res = 1
for i in range(1, self.n):
yield res
res *= i
def m(self):
s = []
for i in self.Factorial():
s.append(i)
return s
b = a(100)
print(b.m())
CodePudding user response:
It seems that you do not know what self is. It's actually like 'this'. In a class, it is the first parameter of the functions. However, you do not have to pass it; it is automatically passed when using the . operator on a class instance (here self
and m
are instances of the class)
class a:
def __init__(self, n):
self.n = n
def Factorial(self):
res = 1
for i in range(1, self.n):
res *= i
yield res
def m(self):
s = []
for i in self.Factorial():
s.append(i)
return s
print(a(100).m()) # a(100) creates an instance (calls __init__ with param n=100
CodePudding user response:
There is no problem with using a generator that has been defined in the class in which it is being used.
Your code has a 2 errors:
- When you are calling
range
onFactorial
method, you are passingself
as range limit instead ofself.n 1
, as factorial of a natural number n is defined as: n × (n - 1) × (n - 2) × ... × 2 × 1. - You are calling
self.iter
which is not valid Python syntax (as you have not defined aniter
method to your class). You should usefor m in self.Factorial():
.
Solve those and your code should work!