1

I'm trying to create a 'Polynomial' class in python, it takes an np array with polynomial coefficients as input, and needs to allow this attribute to have a 'get' and 'set' property, I'm trying to achieve this using decorators. However, when I create an instantiation of the Polynomial object it seems as though it is not using my @coefficients.setter method, because it doesn't print the string 'setting coefficients' nor does it seem to use the @coefficients.getter method as it doesn't print its string either. Am I perhaps using the decorators incorrectly? I'm using spyder as my IDE, could that be the cause of the problem?

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

So, as an example:

 \>>fx = Polynomial([0,0,1])

won't print 'setting coefficients', and

\>>fx.coefficients

won't print 'getting coefficients' also when I try to use the order attribute in other methods, I get an error saying that Polynomial has no attribute order.

  • Is your indentation correct? It does matter in Python and your `def __init__()` seems to have an extra space in front of it. Also, a point on the style, try to follow [PEP 8 - Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/). – zwer May 18 '18 at 12:27
  • I'm sure my indentation is fine, the initializer is definitely being called, however, thank you for the style recommendation, it'll definately come in handy in the future. – TrendyParker May 18 '18 at 12:32
  • Could you show exactly how you're using the class, what output you get, and what you expect? – glibdud May 18 '18 at 12:43

1 Answers1

0

I found an answer to my question, in turns out that classes need to inherit from object in order to use the 'setter' and 'getter' decorators, i.e. my class should look like

class Polynomial(object):
    #....

this was answered in another question: Why doesn't setter work for me?

I don't actually know the details as to why the 'new style' classes in python must inherit from object, if anyone knows the exact answer as to why, I'd be grateful.