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.
– Thiago Krempser
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.
– Woss
@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 Krempser
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.
– Woss