无法调用类中定义的方法

时间:2015-11-11 04:18:34

标签: python

我运行程序时遇到“名称未定义错误”,即使我已经在课程中定义了它。

这是我的Python代码:

class Fraction(object):
    """docstring for Fraction"""
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator

    def show(self):
        print(self.numerator, "/", self.denominator)

    def __str__(self):
        return str(self.numerator) + "/" + str(self.denominator)

    def __add__(self, other_fraction):
        new_numerator = self.numerator*other_fraction.denominator + self.denominator*other_fraction.numerator
        new_denominator = self.denominator*other_fraction.denominator

        common = gcd(new_numerator, new_denominator)
        return Fraction(new_numerator//common, new_denominator//common)

    def gcd(numerator, denominator):
        if numerator % denominator == 0:
            return denominator
        else:
            return gcd(denominator, numerator % denominator)



fraction1 = Fraction(3, 5)
fraction2 = Fraction(8, 9)

print(fraction1 + fraction2)

所以当我执行并捕获错误时,你们可以在上面的代码中告诉我一些错误:

Traceback (most recent call last):
  File "fraction.py", line 31, in <module>
    print(fraction1 + fraction2)
  File "fraction.py", line 17, in __add__
    common = Fraction.gcd(new_numerator, new_denominator)
  File "fraction.py", line 24, in gcd
    return gcd(denominator, numerator % denominator)
NameError: name 'gcd' is not defined

2 个答案:

答案 0 :(得分:0)

您可以将gcd设为实例方法

def gcd(self, numerator, denominator):

并使用self来调用它:

common = self.gcd(new_numerator, new_denominator)

或者,将其设为静态方法:

@staticmethod
def gcd(numerator, denominator):

并称之为:

common = Fraction.gcd(new_numerator, new_denominator)

您可以查看此问题的最佳答案,详细了解实例和静态方法(以及类方法):What is the difference between @staticmethod and @classmethod in Python?

答案 1 :(得分:0)

gcd可能不属于类本身,但这应该使您的代码工作:

def gcd(self, numerator, denominator):
    if numerator % denominator == 0:
        return denominator
    else:
        return self.gcd(denominator, numerator % denominator)