我试图在python中创建一个‘多项式’类,它使用一个带有多项式系数的np数组作为输入,并且需要允许这个属性具有一个'get‘和'set’属性,我试图使用装饰器来实现这一点。但是,当我创建多项式对象的实例化时,它似乎没有使用我的@coefficients.setter方法,因为它没有打印字符串“设置系数”,也没有使用@coefficients.getter方法,因为它也没有打印它的字符串。我是不是不正确地使用装饰师?我正在使用spyder作为我的IDE,这可能是问题的原因吗?
class Polynomial ():
__coefficients = None
def __init__ ( self , coeffs ):
self.coefficients = coeffs
#INTERFACES FOR ATTRIBUTE : __coefficients
@property
def coefficients ( self ):
print('getting coefficients')
return self . __coefficients
@coefficients.setter
def coefficients ( self , coeffs ):
print('setting coefficients')
self . __coefficients = np . array ( coeffs )
self . __order = self . __coefficients . size
@coefficients . deleter
def coefficients ( self ):
del self . __coefficients因此,举个例子:
\>>fx = Polynomial([0,0,1])不会打印“设置系数”,并且
\>>fx.coefficients当我尝试在其他方法中使用order属性时,我也不会打印“获取系数”,我会得到一个错误,说明多项式没有属性顺序。
发布于 2018-05-19 09:29:09
我找到了一个问题的答案,原来类需要从对象继承才能使用'setter‘和'getter’装饰器,也就是说,我的类应该看起来像
class Polynomial(object):
#....这在另一个问题中得到了回答:Why doesn't setter work for me?
我实际上不知道为什么python中的“新样式”类必须从对象继承的细节,如果有人知道确切的答案,我将非常感激。
https://stackoverflow.com/questions/50411171
复制相似问题