Recursive Function Call in OOP Python
So I've recently started doing Object Oriented Programming with Python, and for a specific problem I have to write a class that deals with fractions. Everything seems to be coming along fine with writing methods of common math operators s开发者_如何学Cuch as subtraction and addition; however, I am stuck with a recursive method.
class fractions():
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def GreatestCommonDivisor(self, numerator, denominator): # This is the culprit
if numerator%denominator == 0:
return denominator
else:
return GreatestCommonDivisor(self, denominator, numerator%denominator)
When I call the Greatest Common Divisor function in another method that needs the to find the greatest divisor of the numerator, I get:
Traceback (most recent call last):
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "C:\Program Files (x86)\Wing IDE 101 3.2\src\debug\tserver\_sandbox.py", line 9, in GreatestCommonDivisor
NameError: global name 'GreatestCommonDivisor' is not defined
I call the function like this:
X = fractions(9, 36)
X.GreatestCommonDivisor(X.numerator, X.denominator)
If someone could tell me what the issue here is and how to fix it I would greatly appreciate it, this is my first usage of a recursive function in a class.
This line is where the NameError occurs:
return GreatestCommonDivisor(self, denominator, numerator%denominator)
It should read:
return self.GreatestCommonDivisor(denominator, numerator % denominator)
GreatestCommonDivisor is an instance method, not a global method. You need to do
return self.GreatestCommonDivisor(denominator, numerator%denominator)
But your code seems to show you don't really have object oriented concepts completely grasped yet.
精彩评论