Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to edit a instance variable?

I’m new to python and as I was doing an assignment for class, I got stuck using init method.

class Customer(object):
    def __init__(self, number, name):

        self.name = name
        self.number = number
        self.orders = []
        
        
    def addorder(self, order):
        self.orders.extend(order) 
        return self.orders

    def __str__(self):
        return str(self.orders)


Customer('308','John').addorder((1,2,3,4))

print(Customer('308','John'))

The output is an empty list [].

I want the output to be [1,2,3,4]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What am I doing wrong here?

>Solution :

Keep in mind that each time you "call" a class, you instantiate a new object (this is why in many languages other than Python, this actually requires the keyword new). So, in your example, you’re instantiating two different objects (that don’t share their properties). Instead, you should save them in a variable:

customer = Customer("308", "John")
customer.addorder((1, 2, 3, 4))
print(customer)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading