功能到Python类中

我是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的同一文件夹中打开外壳:


>>> 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


LEATH
浏览 133回答 1
1回答

PIPIONE

MCD是的方法Frazione,但您将其称为全局函数。最简单(也是最简洁的IMHO)修复程序是将其移至类之外,因为它不需要访问任何类或实例成员。所以:def MCD(m, n):&nbsp; &nbsp; if m % n == 0:&nbsp; &nbsp; &nbsp; &nbsp; return n&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return MCD(n, m % n)class Frazione:&nbsp; &nbsp; # as before but without MCD如果你想保持它的类,那么你可能会重写它是反复的,而不是递归调用它self.MCD的__init__。无论如何,这是一个好主意,因为Python对递归的支持很弱。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python