首页 > 解决方案 > 尝试在类中使用函数,但“名称未定义错误”不断弹出?

问题描述

我正在编写一个涉及一些外部函数的类,并将它们以字典的形式存储

class Number:
    def __add__(self,other):
        if self.type_tag == other.type_tag:
            return self.add(other)
        elif (self.type_tag, other.type_tag) in self.adders:
            return self.cross_apply(other, self.adders)

    def __mul__(self,other):
        if self.type_tag == other.type_tag:
            return self.mul(other)
        elif (self.type_tag, other.type_tag) in self.multipliers:
            return self.cross_apply(other, self.multipliers)

    def cross_apply(self,other,cross_funcs):
        #select appropriate function from adders dictionary
        cross_func = cross_funcs[(self.type_tag, other.type_tag)]
        return cross_func(self.other)

    adders = {("com", "rat"):add_complex_rational,
              ("rat", "com"):add_rational_complex
             }
    multipliers = {
              ("com", "rat"):mul_complex_rational,
              ("rat", "com"):mul_rational_complex
             }
             
def add_complex_rational(c,r):
    return Complex_Real_Imaginary(c.real + r.numer/r.denom, c.imag)

def add_rational_complex(r,c):
    return add_complex_rational(c,r)

def mul_complex_rational(c,r):
    r_magnitude = r.numer/r.denom
    r_angle = 0
    if r_magnitude < 0:
        r_magnitude = -r_magnitude
        r_angle = pi
    return Complex_Magnitude(c.magnitude * r_magnitude, c.angle * r_angle)

def mul_rational_complex(r,c):
    return mul_complex_rational(c,r)

但是,每当我尝试运行代码时,错误消息就会'add_complex_rational' is not defined不断出现,我不知道为什么,因为它们已经在文件中定义了。请给我一些提示我哪里出错了,谢谢

标签: python

解决方案


像这样在上课前定义所有函数。发生这种情况是因为您在初始化之前调用了该函数。

def your_function():
    pass

class ClassName:
    pass

推荐阅读