开发者

python private attribute

开发者 https://www.devze.com 2022-12-31 07:02 出处:网络
class A(): def __init__(self): self.__var = 5 def get_var(self): return self.__var def set_var(self, value):
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_va开发者_JAVA百科r)

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

Can anyone explain why result is False?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消