Denis Dubinin
Denis Dubinin

Reputation: 257

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 anyone explain why result is False?

Upvotes: 3

Views: 2162

Answers (1)

Santa
Santa

Reputation: 11547

The property decorator only works on new-style classes. In Python 2.x, you have to extend the object class:

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, the assignment a.var = 10 just binds a new value (10) to a new member attribute a.var.

Upvotes: 4

Related Questions