0

我是 Python 新手,我编写了以下代码:

class Frazione:
    def __init__(self, Numeratore, Denominatore=1):
        mcd=MCD(Numeratore,Denominatore)
        self.Numeratore=Numeratore/mcd
        self.Denominatore=Denominatore/mcd

    def MCD(m,n):
        if m%n==0:
            return n
        else:
            return MCD(n,m%n)

    def __str__(self):
        return "%d/%d" %(self.Numeratore, self.Denominatore)

    def __mul__(self, AltraFrazione):
        if type(AltraFrazione)==type(5):
            AltraFrazione=Frazione(AltraFrazione)
        return Frazione(self.Numeratore*AltraFrazione.Numeratore, self.Denominatore*AltraFrazione.Denominatore)

    __rmul__=__mul__

在 Frazione.py 的同一文件夹中打开 shell:

>>> from Frazione import Frazione 

然后结束

>>> f=Frazione(10,5)

当我按 Enter 时,我收到以下输出:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".\Frazione.py", line 5, in __init__
  mcd=MCD(Numeratore,Denominatore)
  NameError: global name 'MCD' is not defined

PS。我为我的英语道歉!

4

1 回答 1

5

MCD是 的一种方法Frazione,但您将其称为全局函数。最简单(也是最干净,恕我直言)的修复方法是将其移到类之外,因为它不需要访问任何类或实例成员。

所以:

def MCD(m, n):
    if m % n == 0:
        return n
    else:
        return MCD(n, m % n)

class Frazione:
    # as before but without MCD

如果您确实想将其保留在类中,则可以将其重写为迭代而不是递归,并将其称为self.MCDin __init__。无论如何,这是个好主意,因为 Python 对递归的支持相当薄弱。

于 2013-06-01T13:50:08.883 回答