Question:
I'm learning Python3, got to encapsulation and here I can't understand. If I understood correctly, then the __
of the class property indicates that you cannot directly access this method through obj.__variable
, right?
But I can’t make the property private, I tried it through __init__()
, and just create __
in the class body.
Through the setter-getter it works fine, but directly through obj.__variable
they can change and read the value.
Please tell me where I went wrong? I do not want to go further without understanding this important topic.
The 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
Answer:
This is because on the penultimate line ( audi.__number = …
) you are creating a new attribute from the outside , the exact name of which is __number
.
The __number
attribute you created from inside the class actually gets the name _Auto__number
, which is precisely the privacy indicator.
Private attributes are not a hard and fast rule, just a convention. If for some reason you need to access such an attribute, then the programmer can do it.
More details: https://docs.python.org/3/tutorial/classes.html#private-variables