I am learning Python3, I have come to encapsulation and here I cannot understand. If you understand correctly, then __ at the class property says that you cannot directly access this method through obj.__variable , right?

But I can't make a property private, I tried using __init__() and simply creating the class __ body.

It works fine through the setter-getter, but can also directly change the value through the obj.__variable .

Tell me please, where was I wrong? I do not want to go further without understanding this important topic.

Code:

 # Создаем класс Auto class Auto: # Инициализация def __init__(self): self.__number = "" print("Создали класс Auto") # Свойства # Номер автомобиля, сильно приватное свойство, т.к. __ префикс и обратиться напрямую нельзя через obj.__свойство #__number = "" # Сеттер def set_number(self, number): # Валидация данных if len(number) in [7, 8]: self.__number = number else: print("Номер автомобиля неправильный, задайте 7 или 8 цифр.") # Геттер def get_number(self): return self.__number # Создаем объект Audi audi = Auto() # Задаем значение audi.__number через сеттер и считываем через геттер audi.set_number("A777SD77") print(audi.get_number()) # Пытаемся задать или прочитать свойство с сильной приватностью __number напрямую - нельзя, т.к. сильно приватное audi.__number = "L123OX23" print(audi.__number) # Считываем значение изначального __number через геттер, а не созданного извне _Auto__number, оно не изменилось print(audi.get_number()) 

Result:

 Создали класс Auto A777SD77 L123OX23 Process finished with exit code 0 

    2 answers 2

    This is because on the second last line ( audi.__number = … ) you create a new attribute from the outside , the exact name of which is __number .
    The __number attribute you __number from inside the class actually gets the name _Auto__number , which is just an indication of privacy.

    Private attributes are not a hard and fast rule, but simply an agreement. If for some reason you need to access such an attribute, then the programmer can do it.

    Read more: https://docs.python.org/3/tutorial/classes.html#private-variables

    • leovp, thank you very much! Now it is clear :) I then looked at the value of the already new property, and not through the getter, but through the getter the value is old, which means the original __number has not changed, but a new property has been created. # Read the value of the original __number through the getter, and not created from outside _Auto__number, it has not changed print (audi.get_number ()) - Alexander2016

    For the future so that such a question does not arise, use __dict__ to check, as the previous speaker said you have created another attribute. It is enough to assign and then display the contents of the object attributes:

    before assignment:

     __dict__ = {'_Auto__number': 'A777SD77'} 

    after:

     __dict__ = {'_Auto__number': 'A777SD77', '__number': 'L123OX23'}