在Python 2.7中定义类中的函数

时间:2016-06-19 12:46:56

标签: python function class

我尝试在Fraction类中添加一个pgdc函数,以便计算最大公共分数或数字pgdc ...该函数应该是递归的。但是,我一直收到以下错误:

Traceback (most recent call last):
  File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 60, in <module>
    p = a.plus(b)
  File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 35, in plus
    return resultat.simplifier()
  File "C:/Users/jf/Desktop/Python-jEdit_v2/23_fraction.py", line 27, in simplifier
    p = pgcd(self.num, self.den)
NameError: global name 'pgcd' is not defined

此外,

simplifierAttributeError: Fraction instance has no attribute 'simplifier'

也出现以下错误

当我尝试add self.pgcd=pgcdself.simplifier=simplifier

时,让我感到困惑

在不同的地方,它仍然无法正常工作......

# -*- coding: utf-8 -*-
class Fraction():
    # constructeur et attributs

    def __init__(self, num = 0, den = 1):
        self.num = num

        if (den == 0):
            erreur("Dénominateur nul") #fonction d'erreur
        self.den = den

    def __str__(self):
        return str(self.num) + "/" + str(self.den)

    def erreur(message):
        print "Erreur: " + message
        from sys import exit
        exit()
    def pgcd(a, b):
        if a == b: 
           return a
        if a > b: 
            return pgcd(a-b, b)
        else: 
            return pgcd(a, b-a)
    def simplifier(self):
        p = pgcd(self.num, self.den)
        self.num = self.num / p
        self.den = self.den / p
        return self

    def plus(self, f):
        resultat = Fraction(self.num * f.den + self.den * f.num, \
                            self.den * f.den)
        return resultat.simplifier()
    def moins(self, f):
        resultat = Fraction(self.num * f.den - self.den * f.num, \
            self.den * f.den)
        if (resultat.num < 0):
        # changer de signe avant de simplifier
            resultat.num = - resultat.num
            resultat = resultat.simplifier()
            resultat.num = - resultat.num
            return resultat
        else:
            return resultat.simplifier()

    def fois(self, f):
        resultat = Fraction(self.num * f.num, self.den * f.den)
        return resultat.simplifier()
    def div(self, f):
        resultat = Fraction(self.num * f.den, self.den * f.num)
        return resultat.simplifier()



#### CONSOLE ####
a = Fraction(5, 11)
b = Fraction(3, 7)
p = a.plus(b)

1 个答案:

答案 0 :(得分:0)

您需要将self声明为函数的参数,并在想要递归调用pgcd时使用它:

def pgcd(self,a, b):
    if a == b: 
       return a
    if a > b: 
        return self.pgcd(a-b, b)
    else: 
        return self.pgcd(a, b-a)

另外,请在此行中使用pgcd致电self.

p = self.pgcd(self.num, self.den)  #from pgcd(self.num, self.den)