Python阶乘类程序触发RecursionError,请求分析问题原因
Hey there! Let's break down exactly why your class implementation of factorial is hitting that RecursionError—it's a simple mix-up that's sending your code into an infinite recursive loop.
The Core Problem
Look at your fact method: you're using self.n (which you initialized to 1 in __init__) for both your base case check and the multiplication. The problem? You never update self.n during recursion. That means every time the method runs, self.n >= 1 is always True—so the recursion never hits the return 1 base case, and just keeps calling self.fact(n-1) over and over until Python's recursion limit is blown.
You should be using the dynamic parameter n (the one you pass into the method) instead of the static instance attribute self.n. That's the value that decreases with each recursive call and will eventually reach 0 to terminate the loop.
Fixed Code
Here's the cleaned-up, working version of your class—we can even remove the self.n instance attribute entirely since it wasn't serving any useful purpose:
class Factorial: def fact(self, n): # Use the passed parameter n for all checks and calculations if n >= 1: return n * self.fact(n - 1) else: return 1 a = Factorial() print("4! =", a.fact(4)) # Output: 4! = 24
Optional: If You Wanted to Use Instance State (Not Needed Here)
If you were trying to use an instance attribute to track intermediate values (though this is totally unnecessary for a standard factorial), you'd need to update it properly. Here's an overcomplicated example just for context:
class Factorial: def __init__(self): self.current_result = 1 def calculate(self, n): if n >= 1: self.current_result *= n self.calculate(n - 1) return self.current_result a = Factorial() print("4! =", a.calculate(4)) # Output: 4! = 24
But again, the first fixed version is far cleaner and more appropriate for a basic factorial implementation.
Quick Recap
Your original code failed because you leaned on a static instance attribute instead of the dynamic parameter that changes with each recursive step. By switching to use n for your base case check and multiplication, the recursion can terminate correctly.
内容的提问来源于stack exchange,提问作者Vinoth Karthick

