Doubt about Python classes and attributes

Asked

Viewed 92 times

3

I have a question about classes, attributes and objects in Python.

For example using the class below:

class Car:
     drivers = ['João', 'José']
     def allowed_drivers(self):
             print('The list of allowed drivers: {}.'.format(self.drivers))

I make an instance car1 and another instance car2:

car1 = Car()
car2 = Car()

Then add one more item in the attribute drivers:

car1.drivers.append('Francisco')

When I print the attribute drivers of the other object car2:

car2.allowed_drivers()

The result I get is 'The list of allowed drivers: ['João', 'José', 'Francisco'].'

The result should not be 'The list of allowed drivers: ['João', 'José'].' in this case?

  • @Andersoncarloswoss In the answer to the duplicate question you say: "If we change the value of the attribute of one object, the other object will also be changed, because the attribute is of the class." but in this small example https://repl.it/@tkrempser/teste1, that is not what happens.

  • 1

    Yes and it showed me that my answer is incomplete there. With list this happens because it is a type mutable. You don’t do another assignment, you just modify the object. When it’s integer, as shown in the example, it’s a type immutable and you do another assignment to change it, with this the assignment is done only in the instance attribute.

  • @Changeable andersoncarloswoss You mean that the attribute stores only a pointer to the memory address in the case of the list and in the case of an integer, we actually have a number stored in the attribute (immutable)?

  • Thiago, sorry, I was editing there. See if the new information helps you. But no, it has nothing to do with pointers (in Python there are no pointers), but only to modify the value without making a new assignment.

1 answer

3


So drivers is a static property, it does not belong to a specific instance, but the class itself.

To declare a property that belongs to an instance you declare the property in the class constructor init and using the self keyword:

class Car:
    def __init__(self):
      self.drivers = ['João', 'José']

    def allowed_drivers(self):
        print(f'The list of allowed drivers: {self.drivers}')

car1 = Car()
car2 = Car()

car1.drivers.append('Francisco')

car1.allowed_drivers()
car2.allowed_drivers()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.