Simo Sorre
Simo Sorre

Reputation: 3

Function into a Python class

I am new in Python and I wrote the following code:

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__

Open shell at the same folder of Frazione.py:

>>> from Frazione import Frazione 

end then

>>> f=Frazione(10,5)

When I press Enter, I receive this output:

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. I apologize for my english!

Upvotes: 0

Views: 219

Answers (1)

Fred Foo
Fred Foo

Reputation: 363487

MCD is a method of Frazione, but you're calling it as if it were a global function. The easiest (and cleanest, IMHO) fix is to just move it outside the class, because it doesn't need to access any class or instance members.

So:

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

class Frazione:
    # as before but without MCD

If you do want to keep it in the class, then you might rewrite it to be iterative instead of recursive and call it as self.MCD in __init__. That's a good idea anyway, as Python's support for recursion is rather weak.

Upvotes: 5

Related Questions