【发布时间】: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