以下是我的python 2.7控制台的输出。我一直在python 3中编写类似的东西,它按预期工作。那么,为什么我允许进行以下重新分配(在python 2.7中):
>>> class Fola:
... def __init__(self,a,b):
... self._a = a
... self._b = b
... @property
... def a(self):
... return self._a
...
>>> m = Fola('mlem','blib')
>>> m.a
'mlem'
>>> m._b
'blib'
>>> m._a
'mlem'
>>> m.a = 'plip'
>>> m.a
'plip'
>>> m._a
'mlem'
>>> m._b
'blib'
答案 0 :(得分:0)
>>> class Fola(object):
... def __init__(self,a,b):
... self._a = a
... self._b = b
... @property
... def a(self):
... return self._a
...
>>> m = Fola(1,2)
>>> m.a
1
>>> m._b
2
>>> m.a
1
>>> m._a
1
>>> m.a = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute