【问题标题】:Trying to use functions inside a class, but 'name is not defined error' keeps popping up?尝试在类中使用函数,但“名称未定义错误”不断弹出?
【发布时间】:2021-05-09 01:10:21
【问题描述】:

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

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 就会不断出现,我不知道为什么,因为它们已经在文件中定义了。请给我一些提示,说明我哪里出错了,谢谢

【问题讨论】:

  • 请使用完整的错误回溯更新您的问题。
  • 如果你的意思是add_complex_rational,那么在执行类的主体时它还没有定义。只需切换顺序,最后定义类...
  • 谢谢,不知道类中使用的外部函数必须放在类代码之前
  • @Mattmmmmm 所有名称必须先定义,然后才能在 Python 中任何地方使用它们。这与具体的函数或真正的类定义无关
  • 这显示是因为您正在创建类级别结构,即:adders = ...。在导入文件时执行。如果您只是从Number 的成员函数内部访问这些函数,则不会发生这种情况。

标签: python


【解决方案1】:

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

def your_function():
    pass

class ClassName:
    pass

【讨论】:

    【解决方案2】:

    适当地标记方法。 Python 认为add_complex_rational 不在类中,而是一个独立的方法。

    【讨论】:

    • 他们不应该在课堂上。他们没有self 参数。
    • 你必须以Number.add_complex_rational访问它
    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2020-12-03
    相关资源
    最近更新 更多