Python: Accessing attributes from outside the class seems to work all too well

Viewed 31

I'm going through a Python tutorial and I noticed following "Car" class example which got me a bit baffled:

class Car():
    pass

car = Car()
car.seats = 5
print(car.seats)

>>>5

I was not aware class instances are mutable as this little example code shows. So it got me testing a little bit further: At what level are the attributes protected and mutable?

import sys
print(sys.version)
    
class Merc(object):
    def __init__(self,doors):
        self.doors = doors
        self._wheels = 4
        self.__spoiler = 0
                
    @property    
    def spoiler(self):
        return self.__spoiler
            
    @spoiler.setter    
    def spoiler(self, nmb):
        self.__spoiler = nmb
                
    car1 = Merc(4)
    print("1: Car doors : ", car1.doors)
    car1.seats = 5
    car1.__wheels = 5
    car1.spoiler = 1
    print("2: seats     : ", car1.seats)
    print("3: _wheels   : ", car1._wheels)
    print("3.1: __wheels: ", car1.__wheels)
    print("4:   spoiler : ", car1.spoiler)
    car1.__spoiler = 2
    print("4.1: __spoiler: ", car1.__spoiler)   

Output:

3.8.10 (default, Jun 22 2022, 20:18:18) 
[GCC 9.4.0]
1: Car doors :  4
2: seats     :  5
3: _wheels   :  4
3.1: __wheels:  5
4: spoiler   :  1
4.1: __spoiler:  2

I was under the happy impression private and protected attributes could not be touched outside their class, as you see in so many tutorials and blogs online and should therefore be decorated with getter and setter methods. But in this test I did, none of this seems to matter much.

What are the purposes of the private and protected underscores, and even getters and setters, if this all seems irrelevant coding.

0 Answers
Related