Python private attribute

class A():

    def __init__(self):
        self.__var = 5

    def get_var(self):
        return self.__var

    def set_var(self, value):
        self.__var = value

    var = property(get_var, set_var)

a = A()
a.var = 10
print a.var == a._A__var

Can someone explain why the result False?

+3
source share
1 answer

The decorator propertyonly works with new-style classes. In Python 2.x, you need to extend the class object:

class A(object):

    def __init__(self):
        self.__var = 5

    def get_var(self):
        return self.__var

    def set_var(self, value):
        self.__var = value

    var = property(get_var, set_var)

Without the behavior of the new-style class, assignment a.var = 10simply associates the new value ( 10) with the new attribute of the element a.var.

+4
source

Source: https://habr.com/ru/post/1746973/


All Articles