python - 尝试在类中使用函数,但“名称未定义错误”不断弹出?
问题描述
我正在编写一个涉及一些外部函数的类,并将它们以字典的形式存储
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
不断出现,我不知道为什么,因为它们已经在文件中定义了。请给我一些提示我哪里出错了,谢谢
解决方案
像这样在上课前定义所有函数。发生这种情况是因为您在初始化之前调用了该函数。
def your_function():
pass
class ClassName:
pass
推荐阅读
- ruby - 返回方法 local_variables 作为哈希
- python - ModuleNotFoundError:没有名为“selenium”的模块,jupyter notebooks python 参考
- django - 如何将模型值传递给不同应用程序中的基本模板?
- geoserver - GeoServer 2.17 内部错误渲染过程失败
- android - 在 Android 的 Kotlin 对象中保存访问令牌
- python - 找不到适用于 python2 命令的平台独立库
- python - 在 SkLearn 中难以理解训练测试和验证数据的输出
- c++ - 如何创建将由与其关联的名称调用的对象创建函数?
- reactjs - 你可以在没有钩子的情况下使用 React Native RefreshControl 吗?
- git - 如何在 Windows 上获得真正显示存储库拓扑的 git 分支的图形表示?