OOP Python 中的递归函数调用
因此,我最近开始使用 Python 进行面向对象编程,对于一个特定问题,我必须编写一个处理分数的类。减法、加法等常见数学运算符的书写方法似乎一切顺利;但是,我坚持使用递归方法。
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)
当我在另一种需要找到分子最大除数的方法中调用最大公约数函数时,我得到:
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
我像这样调用该函数:
X = fractions(9, 36)
X.GreatestCommonDivisor(X.numerator, X.denominator)
如果有人能告诉我这里的问题是什么以及如何解决它,我会非常感谢,这是我在类中第一次使用递归函数。
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 such 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这一行是 NameError 发生的地方:
它应该是:
This line is where the NameError occurs:
It should read:
GreatestCommonDivisor 是一个实例方法,而不是全局方法。你需要做
但是你的代码似乎表明你还没有真正完全掌握面向对象的概念。
GreatestCommonDivisor is an instance method, not a global method. You need to do
But your code seems to show you don't really have object oriented concepts completely grasped yet.