【发布时间】:2019-11-16 07:42:03
【问题描述】:
我正在尝试创建一个基本的数学编程环境,类似于 sage,但非常基本。我已经定义了类functionClass,以及一个从其基类继承属性functionClass.x 的子类poly。
基类poly 的__init__() 方法除了使用functionClass 的x 之外,还接受一个名为coeffs 的列表(对应于多项式的系数)。
出于某种奇怪的原因,我在对象第一次实例化时收到了 RecursionError: maximum recursion depth exceeded 消息。我有点困惑,因为这一切都发生在poly 的__init__() 方法中......快速指针会很有帮助!
这是我目前所得到的:
import math
import operator
class functionClass:
functions = {0: math.sin, 1: math.cos, 2: math.tan, 3: math.exp, 4: 'identity'}
def __init__(self,option_code=0,x=0):
self._option_code = option_code
self._x = x
@property
def code(self):
return self._option_code
@code.setter
def code(self,new_code):
self._option_code = new_code
@property
def x(self):
return self._x
@x.setter
def x(self,new_x):
self._x = new_x
def f_x(self):
if self.code in self.functions:
return self.functions[self.code](self.x)
def __add__(self,other):
sum = self.f_x() + other.f_x()
return sum
def __sub__(self,other):
difference = self.f_x() - other.f_x()
return difference
def __mul__(self,other):
product = self.f_x() * other.f_x()
return product
def __truediv__(self,other):
quotient = self.f_x() / other.f_x()
return quotient
#class poly(functionClass)-------------------------------------------------------------------------------------------------------
class poly(functionClass):
def __init__(self,coeffs,x):
self.coeffs = coeffs
print(self.coeffs)
self.degree = len(coeffs)
functionClass.x = x
@property
def coeffs(self):
return self.coeffs
@coeffs.setter
def coeffs(self,new_coeffs):#TAKES IN A LIST
self.coeffs= new_coeffs
#test this
def p_x(self):
sum = 0
for i in range(self.degree):
sum = sum + (self.coeffs[i] * math.pow(x,i))
return sum
def __add__(self,other):
pass
def __sub__(self,other):
pass
def __mul__(self,other):
pass
当我运行i=poly([1,1,1],1) 时,我得到了这个:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
i = poly([1,1,1],1)
File "C:\Python\numInt.py", line 76, in __init__
self.coeffs = coeffs
File "C:\Python\numInt.py", line 88, in coeffs
self.coeffs= new_coeffs
File "C:\Python\numInt.py", line 88, in coeffs
self.coeffs= new_coeffs
File "C:\Python\numInt.py", line 88, in coeffs
self.coeffs= new_coeffs
[Previous line repeated 989 more times]
RecursionError: maximum recursion depth exceeded
这不是任何家庭作业或类似内容的一部分,我只是在努力提高我的 Python 技能。
【问题讨论】:
-
您在哪里使用导致问题的示例?
-
什么是回溯?另外,我看不出文档字符串是如何相关的,我很想把它全部编辑出来。里面有什么我们应该真正意识到与问题相关的东西吗?
-
啊,我一会儿就编辑出来!
-
我已经剪掉了
-
让我编辑问题并举一个导致错误的使用示例......
标签: python oop inheritance properties