0

I am trying to find the order of a polynomial. I have created a method called "order" to set self.order to the order of the polynomial it is used on, ie polynomial1.order (p1.order). However, in order to add the order attribute so p1.order can work, I find I need to do p1.order() first. How can I remove this step to make it automatic?

Here is my code, do inform me if there are any other faux pas, I'm new to classes:

class Polynomial(object):

    def __init__(self,*p_coeffs):
        self.p_coeffs = list(p_coeffs)
    def order(self):
        self.order = len(self.p_coeffs)

p1 = Polynomial(2,0,4,-1,0,6)
p2 = Polynomial(-1,3,0,4.5)
p1.order() #<-- this step is the one I want to remove so I do not need to write it for every polynomial
print(p1.order)

Thanks in advance

EDIT: I need to keep my "order" method in the process

1 Answer 1

2

Simply perform all instance initialization that you'd like to automatically occur within the __init__() method.

class Polynomial(object):

    def __init__(self,*p_coeffs):
        self.p_coeffs = list(p_coeffs)
        self.set_order()

    def set_order(self):
        self.order = len(self.p_coeffs)

p_list = [
    Polynomial(2,0,4,-1,0,6),
    Polynomial(-1,3,0,4.5),
    ]

for p in p_list:
    print(p.order)

Output:

$ python test.py
6
4
Sign up to request clarification or add additional context in comments.

3 Comments

Is there not a way for it to be done whilst keeping the "order" method? I was instructed to write it in a separate method...
Thank you very much, I think this is what I was looking for. So if I were to add more such attributes, I would have to add more self."name"() to the initialiser?
Actually, for the sake of clarity, I'd avoid naming instance methods and instance variables the same. Regardless, you perform any desired initialization logic within __init__(). You can set other instance variables (e.g. self.p_coeffs = ...), call instance methods (e.g. self.set_order()), etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.