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