【发布时间】:2013-06-01 13:48:29
【问题描述】:
我是 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。我为我的英语道歉!
【问题讨论】:
-
请注意,建议您使用英文标识符编写代码。这使获得帮助变得更容易,并允许更多人更轻松地阅读您的代码。 (参考:python.org/dev/peps/pep-0008/.)
-
你在找python自带的
fractions.Fraction吗? -
对于标识符我很抱歉!我只是复制并粘贴我的代码。关于这个问题,这是一个练习,所以我不在乎
fractions.Fraction。
标签: python class function python-3.x