函数到Python类

时间:2013-06-01 13:48:30

标签: python class function python-3.x

我是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。我为我的英语道歉!

1 个答案:

答案 0 :(得分:5)

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

所以:

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

class Frazione:
    # as before but without MCD

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