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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
In Python 3, you don't have to do like this.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.