tags:

views:

54

answers:

1
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?

+4  A: 

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.

Santa
Thank you.But i have another question. Why if i just do `print A().var` i got `5`Seems like get method work with property decorator.
puumku
Because `A()` creates a new object of type `A`. And the constructor method initializes the `__var` member attribute to be `5`. The subsequent property access to `.var` queries the newly created `A` object, and returns `5`.
Santa
In Python 3, you don't have to do like this.
Selinap
That is why I prefixed my answer with "In Python 2.x, ...." All user-defined classes in Python 3.x are new-style by default.
Santa